<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"></head><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>
js代码如下
$(document).ready(function() {$("#myform").submit(function(){var username=$("#name").val();var age=$("#age").val();var sex=$("input[name ='sex'][checked]").val();var address=$("#add").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('提交成功!');});});