Jquery練習表單驗證
代碼如下:
<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>
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('提交成功!');
});
});