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;
}