Saurabh Mahajan
Saurabh Mahajan

Reputation: 2969

check all radio groups are checked

I want to know best way to check all the radio button groups are checked in a page. My code -

<div class="radioGroup">
    Question1
    <input type="radio" value="1" name="group1"/>1
    <input type="radio" value="2" name="group1"/>2
    <input type="radio" value="3" name="group1"/>3
    <input type="radio" value="4" name="group1"/>4
</div>

<div class="radioGroup">
    Question2
    <input type="radio" value="1" name="group2"/>1
    <input type="radio" value="2" name="group2"/>2
    <input type="radio" value="3" name="group2"/>3
    <input type="radio" value="4" name="group2"/>4
</div>

<div class="radioGroup">
    Question3
    <input type="radio" value="1" name="group3"/>1
    <input type="radio" value="2" name="group3"/>2
    <input type="radio" value="3" name="group3"/>3
    <input type="radio" value="4" name="group3"/>4
</div>

<input type="button" value="check all radio Group selected"  onclick="validate();"/>

and I wrote a javascript function which works fine but I want a good solution means single selector solution.

function validate(){
    var isNotSelected = false;
    $(".radioGroup").each(function(i,v){
        var grpName = $(this).find("input:first").attr("name");
        if($(this).find("[name='"+grpName+"']:checked").val() == undefined){
            isNotSelected  =true;   
        }
    });
    if(isNotSelected){
        alert("not all checked");   
    }
    else{
            alert("all checked");   
    }


}

Thanks in advance

Upvotes: 0

Views: 81

Answers (2)

adeneo
adeneo

Reputation: 318182

Check if the number of total groups match the number of groups that contain a checked radio button, if so, all groups have been selected

$('.radioGroup').length === $('.radioGroup:has(input:checked)').length

Upvotes: 3

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

You can do

var allChecked = !$('.radioGroup:not(:has(:checked))').length;

demonstration

Upvotes: 4

Related Questions