50

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.

Ivar
  • 6,138
  • 12
  • 49
  • 61
frrlod
  • 6,475
  • 8
  • 31
  • 37

12 Answers12

69

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

Pyzard
  • 451
  • 3
  • 14
Minko Gechev
  • 25,304
  • 9
  • 61
  • 68
  • 2
    +1. Though you could replace the `alert()` with `validate()`. – nnnnnn Apr 15 '13 at 09:05
  • All browsers which supports `addEventListener` (IE9+, check out here https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener) – Minko Gechev Apr 15 '13 at 10:15
  • Use named functions instead of anonymous, because it would be impossible to remove this listener. – Alexander Kim Dec 01 '18 at 14:42
  • 4
    One important detail *e.keyCode* is currently deprecated, the new correct way is *e.key* **References** //e.keyCode https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode //e.key https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key – Juanma Menendez Mar 25 '19 at 03:48
  • 1
    Why is the ```e``` used? and Can we execute the code without it? – iatharva Feb 21 '21 at 09:01
  • @iatharva How will you know what key was pressed if you do not make use of the `event` parameter? – Koray Tugay Aug 28 '21 at 00:06
  • 1
    Should be `.key` not `.code`. If `.code` is used and Enter is pressed on a 10key it will come through as 'NumpadEnter', not 'Enter', but when you use .key it always comes through as 'Enter'. – SendETHToThisAddress Sep 03 '21 at 22:50
7
var elem = document.getElementById("wage");
elem.onkeyup = function(e){
    if(e.keyCode == 13){
       validate();
    }
}

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

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
7

Here is a version of the currently accepted answer (from @MinkoGechev) with key instead of keyCode:

const wage = document.getElementById('wage');
wage.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
        validate(e);
    }
});

function validate(e) {
    const text = e.target.value;
    //validation of the input...
}
Marcus
  • 3,459
  • 1
  • 26
  • 25
1
var input = document.getElementById("todo-item");
input.addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {
        event.preventDefault();
        document.getElementById("sub").click(); 
    }
});
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
1

HTML:
Enter your wage:

<input type="text" id="wage" value ="" onkeypress="myFunction(event)" size=20>

JavaScript:

function myFunction(event) {
    var x = event.code;
    if(x == "Enter") {
        validate();
    }    
}

w3schools - KeyboardEvent code Property

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • Hello and welcome to SO! While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Please read the [tour](https://stackoverflow.com/tour), and [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – Tomer Shetah Dec 19 '20 at 12:03
0

You would need something like wage.addEventListener('keydown', validate);

Your validate function would then need to check event.keyCode == 13 to determine 'enter' keypress.

scottlimmer
  • 2,230
  • 1
  • 22
  • 29
0

If you change your button element to a

<input type="submit" value="Submit">

it will work with the enter button on your keyboard.

gvhuyssteen
  • 292
  • 7
  • 18
0

Or with jQuery

$("#wage").on("keydown", function (e) {
    if (e.keyCode === 13) {  //checks whether the pressed key is "Enter"
        validate(e);
    }
});
klaasjan69
  • 181
  • 2
  • 7
0

It's quite simple. You can do this using keyup event.

$(document).on("keyup", "#wage", function(e) {
  if (e.which == 13) {
    alert("Hi")
  }
})
ulou
  • 5,542
  • 5
  • 37
  • 47
  • This question doesn't mention jQuery. Please before answering, check if it mentions the Library/Programming Language in the tags or the body – Vivaan Oct 10 '21 at 19:17
0

I would suggest using the key attribute of the KeyboardEvent, documentation on that can be found here. You can also make the code much shorter by using a lambda function and an AND (&&) operator.

Here's how I would do it:

document.querySelector('#wage').addEventListener('keypress', e => e.key === 'Enter' && validate(e));

The AND operator first checks whether e.key is equal to 'Enter', and if that is true it executes the validate function. If e.key is not 'Enter' it will not reach the validate function and will not execute it.

Mithras
  • 65
  • 1
  • 9
0

I know there are very nice and different solutions. But I want to add one more thing. Because I didn't see it among the answers.In this situation "onkeydown" can be used.I see a lot of solution with keyup method.

  • It is a DOM Level 2 (2001) feature.

  • It is fully supported in all browsers.

  • The onkeydown() method runs when a keyboard key is pressed. The onkeyup() method works when a finger is lifted from a keyboard key.

       document.querySelector("#wage").onkeydown = (e) => {
           if(e.keyCode === 13){  //enter
       document.querySelector(".add").click();
        }
          if(e.keyCode === 46){ // delete
       document.querySelector(".delete").click();
       }};
    
-1
$(document).on("keyup", function(e) {
    var key = e.which;

    if (key == 13) // the enter key ascii code
    {
        login();
    }
});
Peter
  • 10,492
  • 21
  • 82
  • 132
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Brett DeWoody Mar 27 '18 at 08:53
  • I'm downvoting this for 2 reasons: 1) there is no explanation. 2) this event will trigger on every keypress on every object and the login will execute anytime Enter is pressed anywhere, but the event should only be triggered on 1 or more specific elements. – SendETHToThisAddress Sep 03 '21 at 22:45