jquery enable submit button

How to Enable Submit Button using jQuery

Have you ever encountered a situation where you have a form with a disabled submit button and you want to enable it dynamically based on some condition? Well, you can easily achieve this using jQuery.

Method 1: Using the prop() Method

The prop() method sets or returns properties and values of the selected elements. We can use it to enable or disable the submit button based on some condition.

$(document).ready(function(){
   $('#myForm').submit(function(){
      if(condition){
         $('#submitBtn').prop('disabled', false);
      } else {
         $('#submitBtn').prop('disabled', true);
      }
   });
});
  • The code above uses the submit() method to attach an event handler to the form submit event.
  • It then checks for a certain condition and enables/disables the submit button using the prop() method.
  • The true value passed as the second parameter disables the button whereas false enables it.

Method 2: Using the attr() Method

The attr() method is used to get or set attributes and their values of the selected elements. In this case, we will use it to enable or disable the submit button by setting its disabled attribute.

$(document).ready(function(){
   $('#myForm').submit(function(){
      if(condition){
         $('#submitBtn').removeAttr('disabled');
      } else {
         $('#submitBtn').attr('disabled', 'disabled');
      }
   });
});
  • The code above uses the submit() method to attach an event handler to the form submit event.
  • It then checks for a certain condition and enables/disables the submit button using the removeAttr() and attr() methods respectively.
  • The removeAttr('disabled') method removes the disabled attribute from the button whereas attr('disabled', 'disabled') sets it to 'disabled'.

Both methods work just fine. However, the prop() method is recommended over the attr() method for handling boolean attributes such as disabled.

I hope this helps you enable your submit button dynamically using jQuery.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe