jQuery and radio button groups
Asked Answered
B

3

17

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.

Bernardobernarr answered 22/7, 2009 at 14:21 Comment(0)
T
37

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'))
}
Taam answered 22/7, 2009 at 15:4 Comment(3)
what does !! stand for and why?Horologist
Duble NOT, it converts boolean value two times in a row so !!true = trueOmasum
I know this is old, but this has helped me out so much! I just wanted a simple way to ensure that each of my radio button groups was selected, and here it is.Sociometry
F
0

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/

Featherstone answered 30/9, 2012 at 11:27 Comment(0)
P
0

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.

Purveyor answered 5/4, 2016 at 22:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.