Many times in our program, we may need to disable or enable a button in our webpage based on certain conditions being fulfilled or not, and for that, we must be aware about the ways how to do it.
The button element is one of the few elements in HTML that can have its state, i.e., either being enabled to accept a click or it could be disabled.
For example - Suppose we are asking the user to fill out a form on our website, and we only want to enable the submit button when the user has clicked on the 'They have read the terms and conditions' option, or they have filled some mandatory input field. So in order to do that, we have a particular property associated with every button element in HTML, the disabled property. We can use the disabled property to toggle the state of a button's activeness to be either true or false, and through this, we can enable or disable a button.
Let's understand it better with the help of an example.
After having the button, we can now use the disabled property to make its state active or inactive. To make it inactive, we can set its value to true.
And to make it active again, we can simply set its value to false.
We will not be hardcoding enabling or disabling buttons like this in actual programs; we want this to happen automatically when a specific condition is being met.
Now let's see an example to understand it better.
Output before clicking the button
Output after clicking the button
We can see that after clicking the button, the disableButton() function got executed, and it made the button's background gray out, denoting it is now not clickable, i.e., the button is disabled now.
Output before selecting checkbox
Output after selecting checkbox
We can see here the submit button is disabled by default, and it gets clickable only after the user has selected the required checkbox.
- Every button element in HTML has a property named disabled to toggle its state of activeness and inactiveness.
- For that, we first need to capture that specific button using query selectors, and after that,
- We can set the button.disabled = true; to disable that button and button.disabled = false; to enable it back again.
- We can use this implementation to make a button active or inactive based on certain specific conditions being met or not, for example - enabling the submit button only if the user has filled all the mandatory fields, etc.