1,jquery 表单验证的html部分
<body> <form action="" method="post" id ="myform"> <table> <tr> <td>姓名:</td> <td><input type ="text" id = "name" name ="name"></td> </tr> <tr> <td>年龄:</td> <td><input type ="text" id="age" name ="age"></td> </tr> <tr> <td>性别:</td> <td><input type = "radio" id="sex_man" name="sex" value="男">男 <input type = "radio" id="sex_woman" name="sex" value = "女" checked ="checked">女</td> </tr> <tr> <td>地址:</td> <td> <select id = "add"> <option values="北京">北京</option> <option values="河南">河北</option> <option values="河南">河南</option> </select> </td> </tr> <tr> <td>爱好:</td> <td> <input type ="checkbox" id = "cbOnTheInternet" name="checkbox" value ="上网" checked="checked">上网 <input type ="checkbox" id = "cbJuketing" name="checkbox" value="旅游">旅游 <input type ="checkbox" id = "cbWatchingTv" name="checkbox" value="看电影">看电影 </td> </tr> <tr> <td><input type ="submit" value="提交"></td> </tr> </table> </form> </body> </html>
2,Jquery部分
$(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();// or docEl.value }); if(username=="") { alert("性名不能为空!"); $("#name").focus(); return false; } if(age=="") { alert("年龄不能为空"); $("#age").focus(); return false; } if(size==0) { alert("未选择爱好"); $("input[name='checkbox']").get(0).focus(); return false; } for(var i=0;i<favouriteArray.length;i++){ alert(favouriteArray[i]); } alert('提交成功'); }); });