验证单选按钮

时间:2013-06-06 11:57:38

标签: javascript radio

我的验证仅适用于一个单选按钮,所有左侧单选按钮在此处不起作用是我的代码

    <script>
function xyz()
{
var x = document.getElementsByName("red");
//alert(x.length);

   for (var i=0; i<x.length; i++)
    {
        if (x[i].checked) {
        return true;
    }else{
    alert("fe");
    return false;
    }
  }
}
</script>

<form name="as" method="post" action="n.php">
<input type="radio" id="x1"   name="red">
<input type="radio"  id="x2"   name="red">
<input type="radio"   id="x3"  name="red">
<input type="radio"   id="x4"  name="red">

<input type="submit" value="button" onclick="return xyz()">
</form>

3 个答案:

答案 0 :(得分:1)

你应该试试这个。

function xyz()
{
    var x = document.getElementsByName("red");
    for (var i=0; i<x.length; i++)
    {
        if (x[i].checked) {
            return true;
        }
    }
    // No radio button checked, return false.
    return false;
}

答案 1 :(得分:0)

首次运行后,您的功能将返回任一状态。要跳到下一个迭代元素,您应该使用continue而不是return。见:http://www.w3schools.com/js/js_break.asp。迭代扔掉你要做的所有元素:

for (var i=0; i<x.length; i++) {
    if (x[i].checked) {
        // Do something if checked
    } else {
        // Do something if not checked
        alert("fe");
    }
    // Continue to next element
}

答案 2 :(得分:0)

请尝试以下代码:

<script type="text/javascript">
function validate()
{
var checked = null;
var inputs = document.getElementsByName('correct');
for (var i = 0; i < inputs.length; i++) 
{
      if (inputs[i].checked) {
       checked = inputs[i];
   }
}
if(checked==null)
{
    alert('Please choose an option');
    return false;
}
else
{
    return confirm('Save As Correct Answer '+checked.value+'');
}
}   
</script>

<form method="post" name="Form" onsubmit="return validate()" action="">
<input type="radio" name="correct" id="correct" value="A">
<input type="radio" name="correct" id="correct" value="B">
</form>