如何通过javascript验证单选按钮?
Male <input type="radio" name="sex" value="male" />
female <input type="radio" name="sex" value="female" />
如何通过javascript验证单选按钮?
Male <input type="radio" name="sex" value="male" />
female <input type="radio" name="sex" value="female" />
尝试以下,包括 jQuery
$(document).ready(function(){
$('#submit').click(function() {
if (!$("input[@name='sex']:checked").val()) {
alert('Nothing checked!');
return false;
}
else {
alert('A radio button is checked!');
}
});
});
你的 html 应该是这样的
<form method="post" id="form">
Male <input type="radio" name="sex" value="male" />
female <input type="radio" name="sex" value="female" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
记得包含 jQuery api 的
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.2.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.js" type="text/javascript"></script>
我认为您正在寻找所需的验证:检查以下代码:
<html>
<head>
<script language='javascript'>
function submit_form(){
var temp=document.getElementsByName("gender");
if(temp[0].checked == true || temp[1].checked == true )
{
document.forms["f1"].submit();
}
else
{
alert("Please Select a Gender");
}
}
</script>
<body>
<form id="f1" action="custom.html" method="post">
<input type="radio" name="gender" value="male"/>
<input type="radio" name="gender" value="female"/>
<input type="button" id="s1" onclick="submit_form()" value="Submit" />
</form>
</body>
</html>