jQuery equivalent "on (release, keyPress "<Enter>") {"

Discussion in 'jQuery' started by Kyriakos, Jun 18, 2013.

  1. #1
    Hi.
    i want to send some variable with jQuery but i have only a script for "onclick" function. i want also to send the variable on keypress "enter". equivalent of flash actionscript code: "on (release, keyPress "<Enter>") {"
    this is my script:
    $(function() {
    $("#sendmail").click(function() {
     
    var email = $("#email").val();
    var dataString = 'email='+email;
     
    if(email != '') {
    $.ajax({
    type: "POST",
    url: "sendmail.asp",
    data: dataString,
    cache: false,
    success: function(html){
    $("#email").val("");
    }
    });
    } return false;
    }
    });
    });
     
    <input id="email" type="text"/><input value="Submit" id="sendmail" type="submit"/>
    Code (markup):
    how i can send the variable onClick or onEnter?
    thanks in advance
     
    Last edited: Jun 18, 2013
    Kyriakos, Jun 18, 2013 IP
  2. HuggyStudios

    HuggyStudios Well-Known Member

    Messages:
    724
    Likes Received:
    20
    Best Answers:
    26
    Trophy Points:
    165
    #2
    You need to use: http://api.jquery.com/keypress/

    I've written this code below, it's tested and works fine.

    
    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Enter key press</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(function() {
       //$("#sendmail").click(function() { old click event
       $("#email").keypress(function(event) { // new keypress event
           if(event.which == 13 ) { // 13 is the enter key
               event.preventDefault();
               var email = $("#email").val();
               var dataString = 'email='+email;
               if(email != '') {
                   $.ajax({
                   type: "POST",
                   url: "sendmail.asp",
                   data: dataString,
                   cache: false,
                       success: function(html){
                           $("#email").val("");
                       }
                   });
               }
               return false;
           }else{
               return true;    
           }
           
       });
    });
    </script>
    </head>
     
    <body>
    <input id="email" type="text"/><input value="Submit" id="sendmail" type="submit"/>
    </body>
    </html>
    
    Code (markup):
    Let me know how it goes.
     
    HuggyStudios, Jun 18, 2013 IP