Check if at least one option is selected in a form with radio buttons and checkboxes
Following this thread here I was able to add a validation to a form with both radio buttons and checkboxes: if at least one option per each question is selected, the submit button is enabled.
here is the code:
$('开发者_开发技巧input:submit').attr('disabled',true);
var input_groups = {}
$("input:radio, input:checkbox").each(function(){
$(this).attr('checked', false);
input_groups[this.name] = true;
});
$('input:radio, input:checkbox').change(function() {
var submission = true;
for(group in input_groups){
is_checked = !!$("[name=" + group + "]:checked").length
if(!is_checked){ submission = false;}
}
if (submission){
$("label[for='submit']").html('You are ready to submit!');
$('input:submit').attr('disabled',false);
}
});
It works, but if I accidentally deselect a checkbox, the submit button stays enabled...I am probably missing something obvious...
Any suggestion?
Thank you
In the onchange handler you check if there's anything checked and enable the submit button, but you forgot to disable it if the check fails:
if (submission){
$("label[for='submit']").html('You are ready to submit!');
$('input:submit').attr('disabled',false);
} else {
$("label[for='submit']").html('You are NOT ready to submit!');
$('input:submit').attr('disabled',true);
}
Your code:
if (submission){
$("label[for='submit']").html('You are ready to submit!');
$('input:submit').attr('disabled',false);
}
This only gets executed if submission is false, so it's not setting disabled. Refactor to:
if (submission){
$("label[for='submit']").html('You are ready to submit!');
}
$('input:submit').attr('disabled',!submission);
精彩评论