Jquery 연습 폼 검증 실현 코드

2963 단어 폼 검증
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(' !');
});

});

좋은 웹페이지 즐겨찾기