I only have 1 input field and I want to register onChange and onKeyPress event to detect when the users finish their input or press the Enter key. I need to use javascript only. Thanks for the help.
I have:
var load = function (){ //I want to trigger this function when user hit Enter key. } document.getElementById('co').onchange=load; //works great document.getElementById('co').onKeyPress=load; //not sure how to detect when user press Enter
html
//no form just a single input field <input type='text' id='co'>
In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.
To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.
The keyup event occurs when a keyboard key is released.
document.getElementById('foo').onkeypress = function(e){ if (!e) e = window.event; var keyCode = e.code || e.key; if (keyCode == 'Enter'){ // Enter pressed return false; } }
DEMO
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