With jQuery, you can disable a button on click event, on page load etc.
This article will explain 2 different ways to disable a button after click using jQuery using its id.

If a button is disabled, it will not perform any action when clicked.

Disabling a button is required when you do not want the same action to be performed again and again or too frequently.
Suppose a form contains a submit button. You would not want the form to be submitted to the server again and again if the user keeps on pressing submit before the form is actually submitted.
The solution is to disable the button on click or when form submit action is performed and enable it after the form is properly submitted.

Method 1: Using attr function

attr function is used for setting or modifying the value of an element attribute. Use this function to set the disabled attribute of a button.
Setting disabled attribute of an element to true disables it. Thus, when a button is clicked, set its disabled attribute to true. Example,

<head>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
  <button id="check" onclick="submit()">Disable</button>
</body>

<script>
  function submit() {
    $("#check").attr('disabled', true);
  }
</script>

Above example loads jQuery library from its CDN, creates an HTML button and associates a function that is called when the button is clicked.

Inside this function, the button is selected using its id and its disabled attribute is set to true. You can also select the button using its class or any valid jQuery selectors.
This method can also be used to enable button. For enabling the button, set the disabled attribute to false. This method works for submit button and for normal buttons as well.

Method 2: Using prop function

This method is similar to the above method but it uses prop function instead of attr to set disabled property of button.
If this property is set to true, then the button will be disabled. If it is false, the button will be enabled. Example,

<head>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
  <button id="check" onclick="submit()">Disable</button>
</body>

<script>
  function submit() {
    $("#check").prop('disabled', true);
  }
</script>

Both the methods explained in this article can be used to enable disable button in jQuery on click.
Click the clap if the article was useful.

Leave a Reply