Wednesday, February 22, 2012

How to use link submit form with jquery?

 In this demo, The Form have two elements.

 The First:

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

 this element will send string that your input to server when you have submitted.

 The second:

<a id="linkId" href="#">Submit Link</a>

 Tag a will be bind a click method with jquery.The click action will execute Form's submit method.
 Tip:the end of the click method must add a sentence "return false;" that will disable the href action after clicked the link.

 When the page on loading, We need to bind two methods use jquery.

 The First:

 For this demo case, I have binded the submit method to Form use to show the first name input when submitting.
 This binding is optional.

 The Second:

 We need to bind a link click action, For submit when click the link.

 In this case, the Form don't submit to server side.
 If your want to submit your request to server side, Please change two places.

 The one:

   The action of the Form's parameter, change it to a server side url.

 The second:

   remove the "return false;" line in source code line8.

DEMO


Submit Link

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(){
        alert($("#firstName").val());
        return false;//remove this line will submit request to server site.
    });
    $("#linkId").click(function(){
        $("#myForm").submit();
        return false;
    });
});
</script>
</head>
<body>
 <form id="myForm" method="post" action="">
    <input type="text" name="firstName" id="firstName"/>
    <a id="linkId" href="#">Submit Link</a>
 </form>
</body>
</html> 

Related Articles
jquery disable button

3 comments: