I'm dynamically pulling and displaying radio button quesitons on a form (separated into different sections by jquery tabs).
So there are lots of 2, 3, 4, 5 etc radio buttons together, which have the same 'name' but different ids.
When you hit next between the sections, I want to check that at least one radio button has been selected for each group.
( When the form loads, the radio buttons have none checked by default and it has to be this way. )
I can loop through the current section's radio buttons but I'm not sure how to easily check that one has been checked for each group?
Using Input Radio checked property: The Input Radio checked property is used to return the checked status of an Input Radio Button. Use document. getElementById('id'). checked method to check whether the element with selected id is check or not.
And the JavaScript: jQuery("#radio_1"). attr('checked', true);
What you should do is set up two variables, both of them serving as boolean flags. Then loop through each set of radio buttons in order to determine if a button has been selected. If so, set the corresponding flag to true, otherwise false. Then at the end, test to see if both flags have been set to true.
In the absence of any relationship between elements, or how to find the group names, I can only give you a pointer, but this should work (the check's triggered by clicking on the element of id="nextButton"
, but obviously this can be customised to any other appropriate event, such as $('form').submit()
, for example):
$(document).ready(
function(){
$('#nextButton').click(
function(){
var radioName = something; // use this if there's a relationship between the element
// triggering this check and the radio buttons
if ($('input[name='+ radioName +']:checked').length) {
// at least one of the radio buttons was checked
return true; // allow whatever action would normally happen to continue
}
else {
// no radio button was checked
return false; // stop whatever action would normally happen
}
}
);
}
);
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