Home > Enterprise >  Input checkbox is registering my console.log but not the rest of the function
Input checkbox is registering my console.log but not the rest of the function

Time:08-10

code:

  if ($("#emotion51 input:checkbox:checked").length < 1) {
        console.log("checked<1");
        $("#step4 button[type='submit']").addClass("disabled");
    } else {
        $("#step4 button[type='submit']").removeClass("disabled");
    }

This is the code I am running. I want to remove the class "disabled" if more than 1 checkbox is checked, the console.log message appears but the addClass doesnt work if I check 1 or more checkboxes.

I basically run a form with steps, each step has a "next step" button and I want to add this validation process to the checkboxes in order for the user to proceed to the next step, but the addClass isnt working to remove the "disabled" class.

am I approaching this the wrong way?

CodePudding user response:

As your function only works as the page loads you have to have an eventListener. As I do not know how your HTML works I made an example with the little information you provided. This probably will not work on every step of your form.

if ($("#emotion51 input:checkbox:checked").length < 1) {
        console.log("checked<1");
        $("#step4 button[type='submit']").addClass("disabled");
    } else {
        $("#step4 button[type='submit']").removeClass("disabled");
    }
    
    
    $('body').on('change', 'input[type="checkbox"]', function(){
  
  if ($("#emotion51 input:checkbox:checked").length < 1) {
        console.log("checked<1");
        $("#step4 button[type='submit']").addClass("disabled");
    } else {
        $("#step4 button[type='submit']").removeClass("disabled");
    }
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="emotion51">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</div>
<div id="step4">

<button type="submit">Submit</button>
</div>

  • Related