0

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

Community
  • 1
  • 1
Paranoid Android
  • 4,672
  • 11
  • 54
  • 73
  • Your code can be greatly compacted by the way. Whenever you test for a boolean and then use that same boolean in your next statement is an area to compact. Also, you want to break out of your `for` loop when you've reached a failed state (no reason to continue). – Adam Terlson Apr 18 '11 at 16:51
  • You are right Adam. I was trying to make it work before optimizing. – Paranoid Android Apr 19 '11 at 08:47

2 Answers2

2

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);
}
DarthJDG
  • 16,511
  • 11
  • 49
  • 56
1

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);
Adam Terlson
  • 12,610
  • 4
  • 42
  • 63