lundi 18 décembre 2017

How to disable button when one checkbox is not checked while other checked

Hi I have a form with multiple checkboxes. It should be that when a master option is checked and a suboption is not, the user can not proceed to the next step. I use the code below, but that ensures that when you enable and disable another suboption (of another main option) you can continue to the next step without checking a suboption of another main option.

The checkboxes:

<input name="input_1" type="checkbox" value="1" id="choice_1">
<input name="input_1.1" type="checkbox" value="1.1" id="choice_1_1">
<input name="input_1.2" type="checkbox" value="1.2" id="choice_1_2">
<input name="input_1.2" type="checkbox" value="1.3" id="choice_1_3">
<input name="input_1.3" type="checkbox" value="1.4" id="choice_1_4">

<input name="input_2" type="checkbox" value="2" id="choice_2">
<input name="input_2.1" type="checkbox" value="2.1" id="choice_2_1">
<input name="input_2.2" type="checkbox" value="2.2" id="choice_2_2">

<input name="input_3" type="checkbox" value="3" id="choice_3">
<input name="input_3.1" type="checkbox" value="3.1" id="choice_3_1">
<input name="input_3.2" type="checkbox" value="3.2" id="choice_3_2">

Jquery / Js

$('#choice_1').change(function(){
                if($(this).prop('checked')){

                    if($("#choice_1:checked").length) {
                        $("#field_18_104").hide(200);
                    } 

                      checked = $("#choice_1_1:checked").length || $("#choice_1_2:checked").length || $("#choice_1_3:checked").length || $("#choice_1_4:checked").length;

                      if(!checked) {
                        var $diverror = $( "<div id='error-form' class='error-form'><p>Error text</p></div>" );
                        $("#input_18_26").append($diverror);
                        $('#form_next_button').prop('disabled', true);
                        return false;
                      } else {
                        $( "#error-form" ).remove();
                        $('#form_next_button').prop('disabled', false);
                      }

                } else {
                    $( "#error-form" ).remove();
                    $('#form_next_button').prop('disabled', false);

                    // if($('#choice_18_26_3').prop('checked')){
                    //  $('#choice_18_26_3').prop('checked', false).change();
                    // } 
                }
    });

I also use the js code for the main option and suboptions of options 2 and 3. This causes problems when for example main option 1 is checked without a suboption and main option 2 or 3 is checked with a suboption. Then the button is enabled again.

The user should not be able to continue when a main option is checked without a sub-option.




Aucun commentaire:

Enregistrer un commentaire