How to disable submit button with jQuery

  • 06 January 2020
  • ADM

 

How to disable submit button with jQuery - images/logos/jquery.jpg

 

For a long submit operation or to avoid users clicking twice a submit button, a common solution is to disable the submit button after user clicked on it.

To disable a button using jQuery you need to add the disabled attribute to the button as true.

$("#btnSubmit").attr("disabled", true);

To disable a button using jQuery you need to add the disabled attribute to the button as false

$("#btnSubmit").attr("disabled", false);

or to to remove the disabled attribute.

$("#btnSubmit").removeAttr("disabled");

Code

If the button is a submit type, part of a form, the disable/enable can be done on the form submit event.

If the button is a normal button type, the disable/enable can be done on the button click event.

<!DOCTYPE html>
<html lang="en">
<head>
	<title>How to disable submit button with jQuery</title>
</head>
<body>
<h1>How to disable submit button with jQuery</h1>
<p> </p>
<p> </p>
<h3>Form Example</h3>
<form id="form1" action="#" method="POST">
	<p>
		<label for="username"><b>Username</b></label>
		<input type="text" placeholder="Enter Username" name="username">
	</p>
	<p>	
		<label for="password"><b>Password</b></label>
		<input type="password" placeholder="Enter Password" name="password">
	</p>
    <p>
		<input type="submit" id="btnSubmit" value="Submit"></input>
	</p>
</form>

<p> </p>
<p> </p>

<h3>Button Example</h3>

<input type="button" value="Commit" id="btnTest"></input>
	
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<script>
    $(document).ready(function () {

		//form submit event
        $("#form1").submit(function (e) {

            //stop submitting the form to see the disabled button effect
            e.preventDefault();

            //disable the submit button
            $("#btnSubmit").attr("disabled", true);
			
			//do the actual submit action of the form
			
            return true;

        });
		
		// stand alone button, using click event on the button
		$("#btnTest").click(function (e) {

            //disable the normal button
            $("#btnTest").attr("disabled", true);
			
            return true;
        });
    });
</script>

</body>
</html>

Output

How to disable submit button with jQuery - /images/jQueryDisable.jpg

 

References