If multiple identical EventListeners are registered on the same EventTarget with the same parameters the duplicate instances are discarded. They do not cause the EventListener to be called twice and since they are discarded they do not need to be removed with the removeEventListener method.
To record a keypress event in JavaScript, use the code below: // Add event listener on keypress document. addEventListener('keypress', (event) => { var name = event. key; var code = event.
Using the once option We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.
Are you trying to submit a form?
Listen to the submit
event instead.
This will handle click
and enter
.
If you must use enter key...
document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for enter
}
});
Here is a version of the currently accepted answer (from @Trevor) with key instead of keyCode:
document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for enter
}
});
You could listen to the 'keydown'
event and then check for an enter key.
Your handler would be like:
function (e) {
if (13 == e.keyCode) {
... do whatever ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With