Reputation: 5870
I have a group of radio buttons as given below.
<input type="radio" name="multi[1]" value="value-1">
<input type="radio" name="multi[1]" value="value-2">
<input type="radio" name="multi[2]" value="value-3">
<input type="radio" name="multi[2]" value="value-4">
<input type="radio" name="multi[3]" value="value-5">
<input type="radio" name="multi[3]" value="value-6">
<input type="radio" name="multi[3]" value="value-7">
<input type="radio" name="multi[n]" value="value-n">
<input type="radio" name="multi[n]" value="value-n">
<input type="radio" name="multi[n]" value="value-n">
If this groups are loaded dynamically, then how can we check if the option in every group is selected?
UPDATE:
num_group = 2;
for(i = 1; i <= num_group; i++){
if(!$('input[name="multi['+i+']"]').is(':checked')){
alert('Please select elective subjects '+i+'!');
return false;
}
}
How to calculate num_group dynamically? Here
Upvotes: 0
Views: 726
Reputation: 7991
It really depends on the type of validation that you would like to have.
If you are trying to validate the radio buttons at one specific time, for instance, when a user presses the submit button, you could just go through all the radios fairly simply, something like:
var max_radios = 1; // keep this updated as radio buttons are added
$('#validate').click(function() {
for (i = 1; i <= max_radios; i++) {
console.log('Radio ' + i + ' is ' +
($('[name="multi[' + i + ']"]:checked').val() == undefined ? 'unchecked' : 'checked') + '<br />');
}
})
It's a little trickier if you want to have the validation live as a user adds/clicks the radio buttons. In this case, as soon as a new radio button is added, you want to put up a validation message that indicates that the user should make a selection, and the validation message disappears once a value is selected. Let me know if that's what you wanted.
Upvotes: 1
Reputation: 3932
You have to check that the document
is ready
then bind a change
event to the document.
This takes into account any elements that are dynamiclly loaded (the change
function with still fire on these elements).
$(document).ready(function(){
$(document).on('change', 'input[type=radio]', function(){
console.log($(this).val())
});
});
Upvotes: 1