jquery Practice Form Validation
Copy Code code as follows:
<body>
<form action= "" method= "post" id = "MyForm" >
<table>
<tr>
<td> name:</td>
<td><input type = "text" id = "name" name = "Name" ></td>
</tr>
<tr>
<td> Age:</td>
<td><input type = ' text ' id= ' age ' name = ' age ' ></td>
</tr>
<tr>
<td> Sex:</td>
<td><input type = "Radio" id= "Sex_man" name= "Sex" value= "male" > Male <input type = "Radio" id= "Sex_woman" name= "se X "value =" female "checked =" Checked "> Female </td>
</tr>
<tr>
<td> Address:</td>
<td>
<select id = "Add" >
<option values= "Beijing" > Beijing </option>
<option values= "Henan" > Hebei </option>
<option values= "Henan" > Henan </option>
</select>
</td>
</tr>
<tr>
<td> Hobby:</td>
<td>
<input type = "checkbox" id = "cbontheinternet" name= "checkbox" value = "internet" checked= "checked" > Internet access
<input type = "checkbox" id = "cbjuketing" name= "checkbox" value= "Travel" > Tourism
<input type = "checkbox" id = "CBWATCHINGTV" name= "checkbox" value= "watching movies" > watching movies
</td>
</tr>
<tr>
<td><input type = "Submit" value= "submitted" ></td>
</tr>
</table>
</form>
</body>
jquery Code
Copy Code code as follows:
$ (document). Ready (
function () {
$ ("#myform"). Submit (function () {
var username=$ ("#name"). Val ();
var age=$ ("#age"). Val ();
var sex=$ ("input[name = ' sex '][checked]"). Val ();
var address=$ ("#add option[selected]"). Val ();
var size=$ ("Input[name= ' checkbox '][checked]"). Size ();
var favouritearray=array (size);
$ ("Input[name= ' checkbox '][checked]"). each (function (index,docel) {
favouritearray[index]=$ (This). Val ();//Docel.value
});
if (username== "")
{
alert (The sex name cannot be empty!) ");
$ ("#name"). focus ();
return false;
}
if (age== "")
{
Alert ("Age cannot be null");
$ ("#age"). focus ();
return false;
}
if (size==0)
{
Alert ("You haven't chosen a hobby yet!") ");
$ ("Input[name= ' checkbox ']"). Get (0). focus ();
return false;
}
for (Var i=0;i<favouritearray.length;i++) {
Alert (Favouritearray[i]);
}
Alert (' Commit success! ');
});
});