1
<input type="email" name="email" id="email" style="width:100%;" onkeypress="getMailList($('#email').val())" required>

i needed to call a function only when enter key pressed. I just use kepress event. But it call function all keypress. Thanks in advance.

user3819882
  • 27
  • 1
  • 6
  • Take a look at the event from your `keypress` handler function. The keycode of the key that was pressed should appear in there. – Lix Aug 19 '14 at 12:33
  • Analogical problem here: http://stackoverflow.com/questions/17548454/javascript-how-to-highlight-text-with-pressing-enter-return – JKS Aug 19 '14 at 12:36

5 Answers5

1

If you wish to use jQuery:

$("#email").keyup(function(event){
  if(event.keyCode === 13){
      //Do something
  }
});

13 is the keycode for enter (Other keycodes: http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000520.html)

Blubberguy22
  • 1,344
  • 1
  • 17
  • 29
0

Everybody suggests using jQuery and it's not needed at all in this case. The same for more javascript, it's not needed and will probably make your code less readable.

The only thing you need to do is an an if statement in the html tag.

Just add the following if statement:

if (window.event.keyCode == 13) getMailList($('#email').val())

13 is the keycode for enter.

<input type="email" name="email" id="email" style="width:100%;" 
onkeypress="if (window.event.keyCode == 13) getMailList($('#email').val())" required>
fonZ
  • 2,428
  • 4
  • 21
  • 40
0

Seems like you are already using jquery so try below code:

$('#email').keypress(function(e) {
    if(e.which == 13) {
      var email = $(this).val();
      getMailList(email);
    }
});
Yalamber
  • 7,360
  • 15
  • 63
  • 89
0

There are two approaches:

  1. bind your event onkeypress on the input, checking if the pressed key is 'enter' (char code = 13)
  2. bind your event to the onSubmit event on the surrounding form. The onSubmit event will trigger when pressing enter.

An example for the latter, which is nicer because it allows you to make it work when javascript is disabled:

<form action="/foo/bar" method="post" id="form">
    <input type="email" id="email" name="email" required />
</form>

$('#form').on('submit', function(e) {
    e.preventDefault();
    getMailList($('#email').val());
    // do something else
});
Bjorn
  • 5,272
  • 1
  • 24
  • 35
0

Html:

<input id="typeHere" placeholder = "Type here and Press Enter" type="text" onkeypress="return functionCall(event)"></input>

Jquery:

var functionCall= function(e) {
    if (e.keyCode == 13) {
        var tb = document.getElementById("typeHere");
        alert(tb.value);
        return false;
    }
    else {
     return true;
    }
}

see fiddle here

Suresh PMS
  • 246
  • 1
  • 14