【问题标题】:How to check if a radio button in each group is checked in jQuery?如何检查每个组中的单选按钮是否在 jQuery 中被选中?
【发布时间】:2011-04-02 23:08:33
【问题描述】:

多个组或单选按钮

<h1>Question 1</h1>
<input type="radio" name="radio1" value="false" />
<input type="radio" name="radio1" value="true" /> 

<h1>Question 2</h1>
<input type="radio" name="radio2" value="false" />
<input type="radio" name="radio2" value="true" />

如何在 jQuery 中检查每个组中的单选按钮是否被选中?

谢谢。

【问题讨论】:

    标签: jquery jquery-selectors radio-button


    【解决方案1】:

    我以“GG”为答案投了赞成票。但是,您无需更改 HTML。

    只需按 [name] 选择(应该是唯一的):

    if ($("input[name='radio1']:checked")[0] != undefined && 
        $("input[name='radio2']:checked")[0] != undefined) {
      ...
    }
    

    【讨论】:

      【解决方案2】:

      formdiv 包装每个无线电组:

      <div id="question1">
          <h1>Question 1</h1>
          <input type="radio" name="radio1" value="false" />
          <input type="radio" name="radio1" value="true" />
      </div>
      
      <div id="question2">
          <h1>Question 2</h1>
          <input type="radio" name="radio2" value="false" />
          <input type="radio" name="radio2" value="true" />
      </div>
      

      然后在 jQuery 中:

      if ($('#question1 input[type=radio]:checked')[0] != undefined && $('#question2 input[type=radio]:checked')[0] != undefined) {
          ...
      }
      

      【讨论】:

        【解决方案3】:

        我会这样做:

        var all_answered = true;
        $("input:radio").each(function(){
          var name = $(this).attr("name");
          if($("input:radio[name="+name+"]:checked").length == 0)
          {
            all_answered = false;
          }
        });
        alert(all_answered);
        

        这样您就不需要依赖同级或父级标签。如果您的单选按钮与任何标签混合在一起,它仍然可以工作。你可以play around with it

        【讨论】:

        • 是的,单选按钮确实与其他标签混在一起了。但是你的解决方案奏效了。谢谢。
        【解决方案4】:

        您可以遍历每个问题 (&lt;h1&gt;) 并使用.nextUntil().filter() 查看答案,看看是否有:checked 的答案,如下所示:

        var noAns = $("h1").filter(function() {
                      return $(this).nextUntil("h1").filter(":checked").length == 0;
                    });
        

        这将返回所有未选择收音机的问题,如果您想查看 any 是否没有答案,您可以查看.length,例如:

        if(noAns.length > 0) { 
          alert(noAns.length + " question(s) don't have answers!"); 
        }
        

        You can give it a try here.


        您也可以对此进行一些扩展,例如突出显示遗漏的问题:

        if(noAns.css({ color: "red" }).length > 0) { 
        

        并在下一轮使用$("h1").css({ color: "" }) 清除它,you can give it a try here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-04-23
          • 1970-01-01
          • 2014-09-19
          • 2014-07-02
          • 2016-01-11
          • 2012-06-18
          • 2020-12-04
          相关资源
          最近更新 更多