im trying to make my own chat... so i have an input text field, the submit button, isn't even submit, its just a button.... so when the enter key is pressed, i need the value of the input field to appear in my textarea (which is readonly)...
well look.. make long story short, i just want a basic enter key event handler, i know it works perfectly with submit buttons cus you don't need to program anything at all, its default. but my button is type="button" .... so when you press enter nothing happens... how do i trigger my button by pressing enter?
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.
You can execute a function by pressing the enter key in a field using the key event in JavaScript. If the user presses the button use the keydown to get know its enter button or not. If it enters the key then call the JavaScript function.
addEventListener("keyup", (event) => { if (event. key === "Enter") { console. log('Enter key pressed') } });
key 13 keycode is for ENTER key.
Here is a version of the currently accepted answer (from @entonio) with key instead of keyCode:
HTML:
<input onkeyup="inputKeyUp(event)" ...>
Plain javascript:
function inputKeyUp(e) {
if (e.key === 'Enter') {
// submit
}
}
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