JS checks whether the form input is empty

Source: Internet
Author: User

JS checks whether the form input is empty

This article mainly introduces the sample code for determining whether the form input is empty in JS. If you need it, you can refer to it for help.

The Code is as follows:

// Remove the spaces on both sides of the input string

 

Function trim (s ){

Var count = s. length;

Var st = 0; // start

Var end = count-1; // end

 

If (s = "") return s;

While (st <count ){

If (s. charAt (st) = "")

St ++;

Else

Break;

}

While (end> st ){

If (s. charAt (end) = "")

End --;

Else

Break;

}

Return s. substring (st, end + 1 );

}

 

 

Suppose the form is like this:

The Code is as follows:

<Form action = "testnew.html" name = "form1">

 

Username: <input type = "text" name = "name">

 

Password: <input type = "password" name = "pwd"> <br>

 

<Input type = "submit" value = "submit" onclick = "isEmpty ()">

 

</Form>

 

 

The function can be defined as follows to determine whether the input is null:

The Code is as follows:

Function isEmpty (){

// Form1 is the name attribute in form

Var _ form = document. form1;

 

If (trim (_ form. name. value) = ""){

Alert ("the user name cannot be blank! ");

Return false;

}

If (trim (_ form. pwd. value) = ""){

Alert ("the password cannot be blank! ");

Return false;

}

 

Return true;

 

}

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.