Reputation: 964
In jQuery, I'd like to select all groups of radio buttons where there are no buttons checked.
Or, is there a way in which I can select all radio button groups and iterate through the groups?
I'm dynamically adding N radio button groups to a page and will not know, before hand, what the names of the radio button groups will be.
Upvotes: 17
Views: 16345
Reputation: 42054
To select all radio by group name and obtain only the list of different names:
function selectRadioByGroupName() {
return $.unique($('input:radio').map(function(index, element) {
return this.name;
}));
}
An example snippet:
function selectRadioByGroupName() {
return $.unique($('input:radio').map(function(index, element) {
return this.name;
}));
}
$(function () {
selectRadioByGroupName().each(function(index, element) {
$('body').append($('<p>First Group name is: ' + element + '</p>'));
});
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<form action="">
<p>
Q1:
</p>
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
<br />
<p>
Q2:
</p>
<input type="radio" name="status" value="male"> Single<br>
<input type="radio" name="status" value="female"> Married<br>
<input type="radio" name="status" value="other"> Other
<br />
<input type="button" name="submit_id" value="Submit" onclick="submitAnswers()">
</form>
After getting the different group names it's possible to cycle on them.
Upvotes: 0
Reputation: 16499
To find all radio groups:
var radio_groups = {}
$(":radio").each(function(){
radio_groups[this.name] = true;
})
to find which radio group has checked radio boxes and which hasn't:
for(group in radio_groups){
if_checked = !!$(":radio[name='"+group+"']:checked").length
alert(group+(if_checked?' has checked radios':' does not have checked radios'))
}
Upvotes: 37
Reputation: 2061
Support for multiple groups and pre-checked.
$('input').click(function() {
var $t = $(event.target);
if ($t.hasClass('checked')) $t.removeAttr('checked');
else $('input[type="radio"][name="' + $t.prop('name') + '"]').not($t).removeClass('checked');
$t.toggleClass('checked');
}).filter(':checked').addClass('checked');
```
Proof: http://jsfiddle.net/abrkn/PGW2Z/
Upvotes: 0