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

2023-09-07 09:18:52 作者:释然

多个组或单选按钮

<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 中检查每个组中的单选按钮是否被选中?

How can I check in jQuery that a radio button in each group is checked?

谢谢.

推荐答案

我会这样做:

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);

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

That way you do not need to rely on sibling or parent tags. If your radio buttons are mixed up with whatever tag, it'll still work. You can play around with it.