1

I have an input field and a button on my form, currently I using the button to start a search.

Can I use the button and if the user presses 'Enter' on the form field ?

This is the search input field and button:

<input id='search' name='search' />
<input type='button' name='find' id='find' value='Find'>

and this is the Jquery I'm using for the button.

$('body').on('click', '#find', function(){

How do I add the enter key on the search field as well ?

Thanks

Tom
  • 1,436
  • 24
  • 50
  • you have to make 2 function, 1 for click, and 2 for keypress(13(enter)) – Denny Sutedja Oct 19 '16 at 08:33
  • Possible duplicate of [How to detect pressing Enter on keyboard using jQuery?](http://stackoverflow.com/questions/979662/how-to-detect-pressing-enter-on-keyboard-using-jquery) – P. Frank Oct 19 '16 at 08:35
  • 1
    [This might help](http://stackoverflow.com/questions/699065/submitting-a-form-on-enter-with-jquery") – Rino Raj Oct 19 '16 at 08:50

5 Answers5

4

this works with button and pressing "enter"

<form id="myForm">
    <input id='search' name='search' />
    <input type='submit' value='Find'>
</form>

$("#myForm").submit(function( event ) {
  event.preventDefault();
// your code here
});
Eren Akkus
  • 471
  • 4
  • 11
3

You can use keypress function:

$("#search").keypress(function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});
P. Frank
  • 5,691
  • 6
  • 22
  • 50
0

Try

$('body').on('keypress', '#search', function(e) {
    if (e.which == 13) {
      alert('enter');
    //do stuff
    }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id = "search">
sideroxylon
  • 4,338
  • 1
  • 22
  • 40
0

to check enter key is pressed use the following javascript code

document.onkeydown = function(e) {
   var keyCode = (e.keyCode ? e.keyCode : e.which);
   if (keyCode == 13) {
      //it means that enter key is pressed now you can do your search functionality here
   }
}
Mansoor Akhtar
  • 2,308
  • 2
  • 15
  • 20
0
$('form#login').keypress(function (e) {
   var keyCode = e.keyCode ? e.keyCode : e.which;       
   if (keyCode == 13) 
   {
      e.preventDefault();
      $('form#login').submit();
      return false; 
   }
});
rsmdh
  • 128
  • 1
  • 2
  • 12