Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
120
rated 0 times [  124] [ 4]  / answers: 1 / hits: 126012  / 11 Years ago, mon, april 15, 2013, 12:00:00

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.


More From » events

 Answers
140

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


[#78903] Saturday, April 13, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyaleenag

Total Points: 678
Total Questions: 121
Total Answers: 105

Location: Papua New Guinea
Member since Thu, Jul 9, 2020
4 Years ago
harleyaleenag questions
Thu, May 5, 22, 00:00, 2 Years ago
Wed, Aug 19, 20, 00:00, 4 Years ago
;