Jquery - 遍历所有选中的单选按钮

新手上路,请多包涵

我有一个类似于下面的表格:

 <form id="myForm">
      Question 1:<br>
      <input type="radio" name="question1" value="Yes"> Yes
      <input type="radio" name="question1" value="No"> No
      <br>
      Question 2:<br>
      <input type="radio" name="question2" value="Yes"> Yes
      <input type="radio" name="question2" value="No"> No
      <br>
      Question 3:<br>
      <input type="radio" name="question3" value="Yes"> Yes
      <input type="radio" name="question3" value="No"> No
      <br>
      <input type="submit" value="Submit" name="submit">
</form>

我想使用 jQuery 从所有问题中获取所有选定的单选按钮值,如果所有值都等于“是”,它将发出成功警报,否则将发出失败警报。

这是我写的 jQuery:

 $(document).ready(function(){
   $("#myForm input[type=radio]:checked").each(function() {
       var value = $(this).val();
   });
});

原文由 Nas Atchia 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 428
2 个回答

您可以检查您是否曾经检查过无线电,然后结果是失败,否则成功。

现场演示

result = "success";
$("#myForm input[type=radio]:checked").each(function() {
  if(this.value == "No" && this.checked == true)
  {
     result = "fail";
     return false;
  }
});
alert(result);

原文由 Adil 发布,翻译遵循 CC BY-SA 3.0 许可协议

<!DOCTYPE html>
<html>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<script>
    $(document).ready(function () {

        $('input[type="radio"]').change(function () {
            var iCountTotal;
            var iCountCkedYes;
            iCountTotal = $('input[type="radio"]').length/2;
            iCountCkedYes = $('input[type="radio"][value="Yes"]:checked').length;
            if (iCountTotal != iCountCkedYes) {
                alert('fail')
            }
            else {
                alert('success')

            }
        });

    });

</script>

<body>

    <form id="myForm">
      Question 1:<br>
      <input type="radio" name="question1" value="Yes" checked="checked"> Yes
      <input type="radio" name="question1" value="No"> No
      <br>
      Question 2:<br>
      <input type="radio" name="question2" value="Yes"> Yes
      <input type="radio" name="question2" value="No" checked="checked"> No
      <br>
      Question 3:<br>
      <input type="radio" name="question3" value="Yes"> Yes
      <input type="radio" name="question3" value="No" checked="checked"> No
      <br>
      <input type="submit" value="Submit" name="submit">
</form>
</html>

原文由 Jobelle 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏