Dynamical radio button group validation in jQuery

jim smith picture jim smith · Nov 22, 2011 · Viewed 8.1k times · Source

What is the best way to validate to ensure at least one in every group is checked, so in the following example groups are name1, name2, name3?

Example

<input type="radio" name="name1">
<input type="radio" name="name1"> 
<input type="radio" name="name1"> 

<input type="radio" name="name2"> 
<input type="radio" name="name2"> 
<input type="radio" name="name2">

<input type="radio" name="name3"> 
<input type="radio" name="name3"> 
<input type="radio" name="name3">

I know I can wrap a div around each one and then check each radio button in the div, but I am looking for a more dynamic solution. So, if in future more radio buttons are added, the jQuery code would not need to be altered or the divs would not need to be added - I hope this makes sense.

Answer

Jose Vega picture Jose Vega · Nov 22, 2011

You should use jquery.validate.js library to help you solve this question, check out their demo

If you use the library it would be as simple as,

<input type="radio" name="name1" validate="required:true">
<input type="radio" name="name1">
<input type="radio" name="name1">

<input type="radio" name="name2" validate="required:true">
<input type="radio" name="name2">
<input type="radio" name="name2">

Check out the jFiddle: This finds all the different names for radio buttons and then runs through all those different groups and makes sure that there is at least one checked, if not it will throw an alert.

$('#button').click(function() {
    var names = [];

    $('input[type="radio"]').each(function() {
        // Creates an array with the names of all the different checkbox group.
        names[$(this).attr('name')] = true;
    });

    // Goes through all the names and make sure there's at least one checked.
    for (name in names) {
        var radio_buttons = $("input[name='" + name + "']");
        if (radio_buttons.filter(':checked').length == 0) {
            alert('none checked in ' + name);
        } 
        else {
            // If you need to use the result you can do so without
            // another (costly) jQuery selector call:
            var val = radio_buttons.val();
        }
    }
});