-1

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

    <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>
4

3 回答 3

1

You should try this.

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;
}
于 2013-06-06T12:02:28.633 回答
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
}
于 2013-06-06T12:07:10.157 回答
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>
于 2014-01-09T10:34:54.383 回答