Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when the user presses Enter in an input field

Tags:

javascript

I only have 1 input field and I want to register onChange and onKeyPress event to detect when the users finish their input or press the Enter key. I need to use javascript only. Thanks for the help.

I have:

var load = function (){    //I want to trigger this function when user hit Enter key. }  document.getElementById('co').onchange=load;   //works great document.getElementById('co').onKeyPress=load;  //not sure how to detect when user press Enter 

html

//no form just a single input field <input type='text' id='co'> 
like image 637
FlyingCat Avatar asked Jul 06 '12 15:07

FlyingCat


People also ask

How do you check if keypress is enter?

In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.

How do you trigger click on enter?

To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.

Which of the following event is triggered whenever the user presses Enter key while editing any input field in the form?

The keyup event occurs when a keyboard key is released.


1 Answers

document.getElementById('foo').onkeypress = function(e){     if (!e) e = window.event;     var keyCode = e.code || e.key;     if (keyCode == 'Enter'){       // Enter pressed       return false;     }   } 

DEMO

like image 149
sachleen Avatar answered Oct 22 '22 19:10

sachleen