使用JavaScript进行单选按钮验证

时间:2014-03-08 12:04:37

标签: javascript php forms validation

这是我的表单

   Select Staff : <select name="Staff" id="Staff"><br />
   <option value="Staff">Select Staff</option>

表单的验证就像这个

一样简单
<script type="text/javascript" language="javascript"> 
function validateMyForm ( ) { 
    var isValid = true;
    if ( document.form1.Name.value == "" ) { 
        alert ( "Please type your Name" ); 
        isValid = false;
    }  else if ( document.form1.Staff.value == "Staff" ) { 
            alert ( "Please choose Staff" ); 
            isValid = false;
    } 
    return isValid;
}
</script>

如何使用JS验证单选按钮?

1 个答案:

答案 0 :(得分:2)

<input type="radio" name="question" id="question_yes" value="Yes" />Yes<br>
<input type="radio" name="question" id="question_no" value="No" />No

<script>
if(document.getElementById('question_yes').checked) {
  // yes is checked
}else if(document.getElementById('question_no').checked) {
  // no is checked
}
</script>

这是一个jsFiddle,向您展示它是如何工作的:http://jsfiddle.net/A3fg8/