In this article I will explain with an example, how to disable
Submit button after click 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.
Disabling Submit Button after click using JavaScript
HTML Markup
The following HTML Markup consists of an HTML INPUT Button and an HTML INPUT Submit Button.
When HTML INPUT Button is clicked nothing happens but when HTML INPUT
Submit button is clicked, the
JavaScript onbeforeunload event handler is executed.
Inside the
JavaScript onbeforeunload event handler, a FOR loop is executed over all HTML INPUT elements and the HTML INPUT elements of type
button or
submit are made disabled.
Note: HTML INPUT Button was added only for illustration purposes and when HTML INPUT Button is clicked the page is not redirected or submitted hence you will not experience the Buttons being disabled.
<form action="https://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>
Disabling Submit Button after click using jQuery
Inside the HTML Markup, the following
jQuery JS file is inherited.
1. jquery.min.js
HTML Markup
The following HTML Markup consists of an HTML INPUT Button and an HTML INPUT Submit Button.
When HTML INPUT Button is clicked nothing happens but when HTML INPUT
Submit button is clicked, the
JavaScript beforeunload event handler is executed.
Inside the
JavaScript beforeunload event handler, all the HTML INPUT elements of type
button or
submit are made disabled using
jQuery.
<form action="https://www.aspsnippets.com/">
<input type="button" id="btn" value="Button" />
<input type="submit" id="btnSubmit" value="Submit" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(window).on('beforeunload', function () {
$("input[type=submit], input[type=button]").prop("disabled", "disabled");
});
</script>
</form>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads