. Advertisement .
..3..
. Advertisement .
..4..
This tutorial will show you how to disable an HTML button with two methods. Both disabled attributes and JavaScript can help you achieve the final result.
Guide On How To Disable An HTML Button
Use HTML Disabled Attribute
A disabled attribute is also known as a Boolean attribute, which lets users disable an element or a button from a specific HTML code. It keeps this element unusable from the browser as well.
Disable the button in HTML with the following input:
<!DOCTYPE html>
<html>
<head>
<title> Guide On How To Disable An HTML Button <title>
</head>
<body>
<button disabled="disabled">Sign up</button>
<button type="button" disabled>Click here!</button>
</body>
</html>
It is worth noting that the disabled button and element are always gray in color and look different from other working ones. In this case, an ID or class will enable you to use the disabled attribute.
Another note is that a button tag is a paired one. For this reason, it is vital to use open and closing tags.
Use JavaScript
Disabling a button in HTML with JavaScript requires calling the jQuery one method. You can also use addEventListener
with the once option to use plain JavaScript.
Add a button:
<button>
click me
</button>
Call one method:
$('button').one('click', () => {
$('button').attr('disabled', 'disabled');
});
Once you call this method with ‘click’, you can listen to the button’s click event once. This time, the callback will set its disabled attribute to true.
With plain JavaScript:
const button = document.querySelector('button');
button.addEventListener("click", () => {
button.setAttribute('disabled', 'disabled')
}, {
once: true
});
Get the button with document.querySelector before calling the addEventListener
to add a click listener. Now, call the setAttribute
to set the disabled value in the callback.
Set once to true so that the event emits once only.
If you want to enable this button or element, fetch the element and change its disabled property to false with the following code:
<button id="disabled" disabled>Click here!</button>
document.getElementById("disabled").disabled = false;
Conclusion
A disabled attribute in HTML is built to disable a button or element. Yet, with ID, we can also get this one back. How to disable an HTML button? There are two common methods mentioned above: using a disabled attribute and JavaScript.
Leave a comment