Friday, February 24, 2012

How to use enter key submit form on different input text with jquery?

In this demo, the Form have two input box such as the "firstName" and the "lastName".
Press Enter key on them will triger different submit method.
The very important method is below:
$("form input").keypress(function (e) {
  if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
    if($(this).attr("name") == "firstName"){
      $("#firstNameId").click();
    }
  if($(this).attr("name") == "lastName"){
    $("#lastNameId").click();
  }
  return false;
} else {
  return true;
}
});

This method define in page initial, Set all input elements bind a keypress method that will execute when user focus in and press enter key.

DEMO





Below is the source code:
<html>
<body>
<div class="demo">
<h2>DEMO</h2>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("form input").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            if($(this).attr("name") == "firstName"){
                $("#firstNameId").click();
            }
            if($(this).attr("name") == "lastName"){
                $("#lastNameId").click();
            }
            return false;
        } else {
            return true;
        }
    });
    
    $("#firstNameId").click(function(){
        alert("This is the firstName submit button click event.");
    });
    
    $("#lastNameId").click(function(){
        alert("This is the LastName submit button click event.");
    });
});
</script>
 <form id="myForm" method="post" action="">
    <input type="text" name="firstName" id="firstName" value="firstName"/>
    <input type="text" name="lastName" id="lastName" value="lastName"/>
    <input type="submit" value="FirstName Submit Button" id="firstNameId"/>
    <input type="submit" value="LastName Submit Button" id="lastNameId"/>
 </form>
 </div>
</body>
</html> 

Related Articles
jquery disable button

1 comment:

  1. If you also like the Path of Exile game, you just need Buy POE Currency, you can click to enter our official website, here not only has the cheapest POE Currency, but also the best service and the most enthusiastic customer service, welcome to MMOAH website.

    ReplyDelete