Reputation: 635
I am trying to find a way to validate all of my radio buttons to make sure atleast one of them is checked. The problem is doing it with the names and id's have to remain in the format that they are in. So basically I want to have a way to group all of my radio buttons even with different names and id's.
I understad how to loop for all checked buttons in the table but some are outside of the table, the code is just an example of what I need to do.
<table id="table" width="100%" border="0" cellpadding="5">
<tr>
<td><input type="radio" name="blue" id="blue" value="blue1" /></td>
<td><input type="radio" name="blue" id="blue" value="blue2" /></td>
<td><input type="radio" name="red" id="red" value="red1" /></td>
<td><input type="radio" name="red" id="red" value="red2" /></td>
<td><input type="radio" name="blue" id="green" value="green1" /></td>
<td><input type="radio" name="green" id="green" value="green2" /></td>
</tr>
</table>
Upvotes: 1
Views: 2666
Reputation: 193261
To make sure at least one radio button within table is checked and the one at the top of the page:
if ($('#top-radio').is(':checked') && $('#table :radio:checked').length) {
// valid, something is checked
}
Upvotes: 0
Reputation: 253318
Given your posted html I'd suggest changing the name
of all those posted <input />
elements to colour
(or color
, according to language preference) to clearly associate them together.
However, if that can't be done, and you're able to add a class-name as a means of associating the group:
var allInputs = $('input.colour'),
checked = allInputs.filter(':checked'),
choiceMade = checked.length > 0;
Incidentally:
…I think by adding the class if I checked one, it would check the rest in that class.
No, that behaviour - unchecking one element should another be checked - is entirely dependent on the <input />
sharing a name
attribute and being semantically grouped. It doesn't matter how else you create an association, so long as you don't yourself create that functionality.
Upvotes: 0
Reputation: 64657
Assuming you are going for the HTML5 validation, just make one of them required, and then change it as they go:
<input required type="radio" name="blue" id="blue" value="blue1" />
JS:
$radios = $('input[type="radio"]');
$radios.on('change', function() {
if ($(this).is(':checked')) {
$radios.prop('required', false);
$(this).prop('required', true);
}
});
$('form').on('submit', function(e) {
if ($('input[type="radio"]:checked').length === 0) {
e.preventDefault();
alert("Must check at least one radio");
return false;
}
});
Upvotes: 1
Reputation: 14927
Something like this:
if($('input[type="radio"]:checked').length > 0){
//at least one radio on your page is checked
}
Upvotes: 2