How to check if a radio button in each group is checked in jQuery?
Asked Answered
O

4

19

Multiple groups or radio buttons

<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" />

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

Thank you.

Osteen answered 24/8, 2010 at 2:36 Comment(0)
V
25

Here is how I would do it:

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.

Visor answered 24/8, 2010 at 2:53 Comment(1)
Yes, indeed the radio buttons were mixed up with other tags. But your solution worked. Thanks.Osteen
R
2

You could loop through each question (<h1>) and looking through it's answers using .nextUntil() with .filter() to see if there any :checked ones, like this:

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

This would return all the questions with no radio selected for them, you could check the .length of that if you wanted to see if any don't have answers, for example:

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

You can give it a try here.


You can also extend this a bit, for example highlighting the questions that were missed:

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

and use $("h1").css({ color: "" }) to clear it the next round, you can give it a try here.

Read answered 24/8, 2010 at 2:42 Comment(0)
M
1

Wrap each radio groups with a form or a div :

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

Then in jQuery:

if ($('#question1 input[type=radio]:checked')[0] != undefined && $('#question2 input[type=radio]:checked')[0] != undefined) {
    ...
}
Manzanilla answered 17/9, 2013 at 8:25 Comment(0)
T
0

I upvoted the answer by "GG." However, you don't need to change the HTML.

Just select by [name] (which should be unique):

if ($("input[name='radio1']:checked")[0] != undefined && 
    $("input[name='radio2']:checked")[0] != undefined) {
  ...
}
Thrashing answered 8/12, 2017 at 17:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.