How To Disable Button In Jquery

In this blog post, we will learn how to disable a button using jQuery. Disabling a button is a common requirement
in web development, especially when you want to prevent multiple form submissions or restrict certain actions
on a webpage.

We can disable a button in jQuery by setting its disabled attribute to true.
To set the attribute, we can use the attr() method or the prop() method. Let’s
go through both of these methods in detail.

1. Using the attr() method

The attr() method in jQuery is used to get or set the value of an attribute for the selected
elements. In our case, we want to set the disabled attribute of a button to true.
Here’s an example:

    $("#myButton").attr("disabled", true);
    

In this example, we have selected a button with the ID myButton and set its disabled
attribute to true using the attr() method.

Enable the button

To enable the button again, all you need to do is set the disabled attribute to false:

    $("#myButton").attr("disabled", false);
    

2. Using the prop() method

Another way to disable a button is by using the prop() method. The prop()
method in jQuery is used to get or set the value of a property for the selected elements. It is usually
recommended to use the prop() method over the attr() method when dealing with
boolean attributes like disabled, checked, and selected.

Here’s how you can disable a button using the prop() method:

    $("#myButton").prop("disabled", true);
    

As you can see, the code is very similar to the one using the attr() method. The only difference
is that we are using the prop() method instead of the attr() method.

Enable the button

To enable the button again, simply set the disabled property to false:

    $("#myButton").prop("disabled", false);
    

Conclusion

In this blog post, we have learned how to disable and enable a button in jQuery using both the
attr() and prop() methods. Although both methods work, it is generally
recommended to use the prop() method when dealing with boolean attributes like
disabled.