JavaScript program to disable a button on click

JavaScript program to disable a button on click:

This post will show you how to disable a HTML button on click using JavaScript. We have different properties for a button and using these properties, we can change its state and view.

For changing the current enable/disable state, we need to use the disabled property of a button. It takes one boolean value. If we set true, it will make the button enable and if we set false, it will make the button disabled.

In this post, we will disable the button if the user clicks on it.

We will create one HTML and JavaScript program with only one button. On clicking this button, it will execute one function in the JavaScript code and it will disable the button.

HTML and JavaScript program:

Create one index.html file(you can also have a html file with any other name) and add the below code:

<!DOCTYPE html>
<html lang="en">

<head>
	<title>Button Example</title>
	<script type="text/javascript">
		function buttonClickListener() {
			document.getElementById('button').disabled = true;
		}
	</script>
</head>

<body style="text-align: center;">
	<h1>Click on the button to disable it</h1>
	<button type="button" id="button" onClick="buttonClickListener()">Click Me</button>
</body>

</html>

If you open this file in any web-browser, it will show one button. If you click on the button, it will invoke the buttonClickListener method and this method changes the disabled property of the button. It is accessing the button by using its id, i.e. ‘button’.

It looks as like below after disabled: JavaScript disable button onClick

You might also like: