Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  3] [ 1]  / answers: 1 / hits: 16832  / 8 Years ago, fri, may 13, 2016, 12:00:00

http://codepen.io/abdulahhamzic/pen/YqMQwB


How do I make it so that when I press enter on a text input, it calls a function? I tried using this:


<input type="text" onkeypress="clickPress()">   

But the problem is I only want to press enter to call that function, not press any key. How do I achieve that?


2022 Update: onkeypress is deprecated.
You can use onKeyDown instead


More From » html

 Answers
23

Use a form instead (the submit event only runs once instead of every key press):




// Attach the event handler to the form element
document.querySelector('.js-form')?.addEventListener('submit', e => {
e.preventDefault();
alert(e.currentTarget.myText.value);
});

<form class=js-form>
<input type=text name=myText>
</form>




[#62183] Thursday, May 12, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trayvon

Total Points: 35
Total Questions: 117
Total Answers: 88

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;