Reputation: 87
I have a selection of radio buttons, each set with a different group name. I want any radio buttons with the class 'radio' to be checked to see if any of that group has been selected. If none have been selected then select the last radio in that group and show the variable 'promptOther'. This works, but instead of just showing one promot, its actually showing a prompt for each radio button. How can I limit it to only show one?
$('.radio').each(function() {
var radioName = $(this).attr('name');
if (!$('input[name='+radioName+']:checked').val()) {
$('input[name='+radioName+']:last').parent().after(promptOther);
required = false;
}
else {
$('.required-prompt', this).remove();
required = true;
}
});
Upvotes: 0
Views: 58
Reputation: 49919
You can remember which groups you already handled like:
var handled = []; // Create an array
$('.radio').each(function() {
var radioName = $(this).attr('name');
if( $.inArray(radioName, handled) == -1 ) { // Check if we handled it
if (!$('input[name='+radioName+']:checked').val()) {
$('input[name='+radioName+']:last').parent().after(promptOther);
required = false;
}
else {
$('.required-prompt', this).remove();
required = true;
}
handled.push(radioName); // Push to array
}
});
Upvotes: 1