Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute a function on pressing the enter key in an <input> field?

I have an input and I'd simply like to add an event listener for it to activate a function when I press enter, when the input is focused. How do I do this with pure JS?

Right now I have:

HTML:

Enter your wage:<input type="text" id="wage" value ="" size=20> <button id="sub">Submit</button> 

JavaScript:

var wage = document.getElementById("wage"); wage.addEventListener("change", validate);  var btn = document.getElementById("sub"); btn.addEventListener("click", validate); 

So basically the function validate() activates when I click OR change the text, but I want to call it by pressing enter.

like image 997
frrlod Avatar asked Apr 15 '13 09:04

frrlod


People also ask

How do you submit a form when Enter key is pressed?

To submit the form using 'Enter' button, we will use jQuery keypress() method and to check the 'Enter' button is pressed or not, we will use 'Enter' button key code value. Explanation: We use the jQuery event. which to check the keycode on the keypress.

How can you tell when the user presses Enter an input field?

Answer: Use the keypress event To check whether a user has pressed Enter key while on specific input, you can use the keypress event in combination with the enter key code 13 .


2 Answers

You can use this:

var wage = document.getElementById("wage"); wage.addEventListener("keydown", function (e) {     if (e.code === "Enter") {  //checks whether the pressed key is "Enter"         validate(e);     } });  function validate(e) {     var text = e.target.value;     //validation of the input... } 

Live demo here

like image 168
Minko Gechev Avatar answered Oct 19 '22 10:10

Minko Gechev


var elem = document.getElementById("wage"); elem.onkeyup = function(e){     if(e.keyCode == 13){        validate();     } } 

Working Example http://jsfiddle.net/aMgLK/

like image 20
Kevin Bowersox Avatar answered Oct 19 '22 12:10

Kevin Bowersox