Home > Mobile >  Javascript disabled button does not gets enabled when the form is completed
Javascript disabled button does not gets enabled when the form is completed

Time:07-19

I have a form and I wanted to disable the submit button unless the required fields are filled.

So I added this:

$('#submitBtn').attr('disabled', true);

if ($('#inputMobile').val() != '' && $('#inputEmail').val() != '' && $('#inputPassword').val() != '' && $('#inputPasswordConfirmation').val() != '') {
      $('#submitBtn').attr('disabled', false);
}

Now it works fine and disable the submit button when the page loads but when I fill in the form fields, it does not enable the button however I tried setting the disabled attr to false.

So what's going wrong here? How can I solve this issue?

CodePudding user response:

May be you need to addListener on form? Also you could check solution in similar question

https://stackoverflow.com/a/67961881/19282017

CodePudding user response:

Your code runs once, when the page is loaded, you need action after the user enters data. Use a change event.

You need a way to specify the event on all 4 fields, so give your four input fields a common class, for example registerInput.

<input type="text" >

Do that for all 4 of your fields.

Then specify a change event, selecting that class, so that your test is run every time the user changes one of the fields.

$(".registerInput").change(function() {
  if ($('#inputMobile').val() != '' 
      && $('#inputEmail').val() != '' 
      && $('#inputPassword').val() != '' 
      && $('#inputPasswordConfirmation').val() != '') {
        $('#submitBtn').attr('disabled', false);
  }
});

CodePudding user response:

With this dummy code, I just wanted to show that your code for changing the attribute is completely true. It seems your code doesn't meet the condition in the if statement.

$('#but2').attr('disabled',true)

$('#but1').on('click',() => {
  if(true){
    $('#but2').attr('disabled',!$('#but2').attr('disabled'))
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="but1">Toggle</button>
<button id="but2">Change me</button>

  • Related