In this article I will explain with an example, how to disable Button and Submit button after one click using JavaScript and jQuery.
The script needs to be placed on the web page and it will disable all buttons and submit buttons as soon as any submit button is clicked using JavaScript and jQuery.
JavaScript onbeforeunload event handler
The JavaScript onbeforeunload event handler is executed before the page is unloaded i.e. when page is redirected or submitted to the server.
Disable Submit button after click using JavaScript
The following HTML Markup consists of an HTML Button and an HTML Submit Button. When the Submit button is clicked, the JavaScript onbeforeunload event handler is triggered.
Inside the JavaScript onbeforeunload event handler, a loop is executed over all HTML Input elements and the HTML Input elements of type button or submit are disabled.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form action="http://www.aspsnippets.com/">
<input type="button" id="btn" value="Button" />
<input type="submit" id="btnSubmit" value="Submit" />
<script type="text/javascript">
window.onbeforeunload = function () {
var inputs = document.getElementsByTagName("INPUT");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "button" || inputs[i].type == "submit") {
inputs[i].disabled = true;
}
}
};
</script>
</form>
</body>
</html>
Disable Submit button after click using jQuery
The following HTML Markup consists of an HTML Button and an HTML Submit Button. When the Submit button is clicked, the JavaScript onbeforeunload event handler is triggered.
Inside the JavaScript onbeforeunload event handler, all the HTML Input elements of type button or submit are disabled using jQuery.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form action="http://www.aspsnippets.com/">
<input type="button" id="btn" value="Button" />
<input type="submit" id="btnSubmit" value="Submit" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(window).on(''beforeunload'', function () {
$("input[type=submit], input[type=button]").prop("disabled", "disabled");
});
</script>
</form>
</body>
</html>
Note: HTML Input Button was added only for illustration purposes and when HTML Input Button is clicked the page is not submitted and hence you will not experience the Buttons being disabled.
Screenshot