Wednesday, February 22, 2012

How to disable submit button on form submit with jquery?

In this Demo, The From have three elements.

 The First element:

<input type="text" name="firstName" id="firstName"/>

 This element ust to request the firstName to server side.
 In this case, When user click the submit button webpage will popup this field vlaue.

 The secode element:

<input type="submit" value="Submit enable"/>

 This submit button is visiable by default on page loading.

 The third element:

<input type="reset" value="Reset"/>

 For user easy to test the demo, I have add this button to reset the firstName field and enable the submit button.

 The jquery have three parts, all jquery will initial in page loading.

 The First part:

$("#myForm").submit(function(){
    $("input[type=submit]").attr("disabled","disabled");
    alert($("#firstName").val());
    return false;
 });

 This part will binding the submit action to the ID "myForm" of the Form.
 When the Form is submitting, This part will find the submit button and disable the submit button.
 The next step will use popup to show the first name value.

 Note1:If your page have more than two form, Please use the id get the submit button.Like below:

$("#xxx").attr("disabled","disabled");

 The xxx is the ID of the submit button.

 Note2:Please don't binding a onclick method to submit button use to execute something, Because of the Chrome is not execute the Form's submit method when use jquery binding a click action the submit button.

 This demo have no server side so I have add a line "return false;" to stop the submit.
 If your have server side, Please remove this line  and change the Form's parameter "action" to your server side url.

 The Second part:

$("input[type=reset]").click(function(){
        $("input[type=submit]").removeAttr("disabled");
        $("#firstName").val("");
 });

 This part will binding a click method to a reset button, For enable the submit button and clear the first name field.

DEMO



 Below is the source code:

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#myForm").submit(function(){
        $("input[type=submit]").attr("disabled","disabled");
        alert($("#firstName").val());
        return false;//remove this line will submit request to server site.
    });
    $("input[type=reset]").click(function(){
        $("input[type=submit]").removeAttr("disabled");
        $("#firstName").val("");
    });
});
</script>
</head>
<body>
 <form id="myForm" method="post" action="">
    <input type="text" name="firstName" id="firstName"/>
    <input type="submit" value="Submit enable"/>
    <input type="reset" value="Reset"/>
 </form>
</body>
</html>

Related Articles
jquery disable button

No comments:

Post a Comment