How to Enable/Disable Button using jQuery

Normally, people will press a submit button more than a time to make sure the button is surely clicked. While do so, it will results and cause submission issue and sometimes shows error. To overcome this problem, the only solution is to disables the submit button after user clicked it.

Using jQuery has many features, where it allows you to enable and disable the buttons. By the way, today we will show you how to quickly enable or disable the submit button using jQuery.

To enable or disable a button with jQuery, we have to use those two methods, attr() and removeAttr().

  1. $(‘.enableOnInput’).prop(‘disabled’, true); //TO DISABLED
  2. $(‘.enableOnInput’).prop(‘disabled’, false); //TO ENABLE

To Disable Button

To do so, you have to add a disabledattribute to the submit button, as follows:

$(“#buttonSubmit”).attr(“disabled”, true);

To Enable Button

For this, either you can disabled attribute to false or remove the disabled attribute. Therefore, there are two ways to enable a disabled button. Let’s see how to enable it in 2 methods.

$(‘#buttonSubmit’).attr(“disabled”, false); 

or

$(‘#buttonSubmit’).removeAttr(“disabled”);

For example

<script>

$(document).ready(function(){

$(“#formABC”).submit(function(e){

//stop submitting the form to see the disabled button effect

e.preventDefault();

//disable the submit button

$(“#btnSubmit”).attr(“disabled”,true);

//disable a normal button

$(“#btnTest”).attr(“disabled”,true);

returntrue;

});

});

</script>

Another example for default disabled. On page load, you can set the button be disabled by default. Once the user fills the form, it will enable automatically.

// To Disable Submit Button By Default

$(“input[type=submit]”).attr(‘disabled’,’disabled’);

// When User Fills Out Form Completely

$(“form”).keyup(function(){

$(“input[type=submit]”).removeAttr(‘disabled’);

});

Also, disable submit button on its first click.

$(“input[type=submit]”).click(function(){

$(“input[type=submit]”).attr(‘disabled’,’disabled’);

});

(Visited 94 times, 1 visits today)