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.
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();
}
}
});
$('[name="name1"]:checked').length != 0
Or
$('[name="name1"]').is(':checked')
You could also do something a little more dynamic if you like:
var i = 1;
while ($('[name="name'+i+'"]').length != 0) {
if ($('[name="name'+i+'"]').is(':checked')) {
// at least one is checked in this group
} else {
// none are checked
}
i++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With