Reputation: 1
I am trying to loop through Radio groups and validate that the user has made a selection using Javascript. The radio groups are dynamic so the field names are unknown at runtime, and the number of radio groups will also be unknown. After the user has made a selection for each radio group, then process the form.
Upvotes: 0
Views: 1642
Reputation: 11354
You can have a map to find the field names that are not checked.
function add() {
remaining[this.name] = true;
}
function remove() {
delete remaining[this.name];
}
var form = $(this), remaining = {};
form.find(':radio').each(add).filter(':checked').each(remove);
Then the remaining
variable will be an object that holds the names of the radio group that the user hasn't checked.
If it is an empty object, then the user has selected all groups.
For a working example, look here: http://jsfiddle.net/thai/qtJsJ/1/
Upvotes: 1
Reputation: 1219
with pure javascript you could try something like
var elements = document.getElementsByTagName("input");
for(var i = 0; i<elements.length; i++)
{
if(elements[i].type === "radio")
{
//dostuff
}
}
Upvotes: 0
Reputation: 171
You could select all radio buttons using the 'input:radio' selector and then make sure that for each distinct name a value is set.
$(document).ready(function() {
$(this).find("input:radio").each(...)
}
Upvotes: 0