如何通過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應該廁所K類似於這樣
<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>
我想通過javascript來做 –
我認爲你正在尋找需要驗證: 檢查下面的代碼:
<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>
注:記得's'在函數名 – diEcho