2012-09-14 221 views
0

如何通過JavaScript驗證單選按鈕?驗證單選按鈕

Male <input type="radio" name="sex" value="male" /> 
female <input type="radio" name="sex" value="female" /> 

回答

1

嘗試以下,包括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> 
+0

我想通過javascript來做 –

1

我認爲你正在尋找需要驗證: 檢查下面的代碼:

<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> 
+0

爲什麼你選擇不同的'id'作爲單選按鈕? – diEcho

+0

ID在這裏並不重要...讓我只爲你編輯它。 –

+0

@diEcho - 在一個表格ID應該是唯一的 – Vamsi