Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Enter keypress in html input without jquery

I just want to detect the enter input keypress on my android device. I found out that using jquery, we can do like below:

$('#inputText').keypress(function(event) {
var keycode = event.keyCode || event.which;
if(keycode == '13') {
    alert('You pressed a "enter" key in somewhere');    
}
});

But I don't want to use jquery. I want to use the traditional way like using

document.getElementById('inputText')

But I don't know how to add in the keypress event function. Do you guys have any idea?

like image 652
Coolguy Avatar asked Jan 18 '26 02:01

Coolguy


1 Answers

Almost the same as in jQuery. Use eventListener and pass an argument e to the function to catch the event and it's keyCode.

var elem = document.getElementById('inputText');
elem.addEventListener('keypress', function(e){
  if (e.keyCode == 13) {
    console.log('You pressed a "enter" key in somewhere');   
  }
});
<input id='inputText'>
like image 108
kind user Avatar answered Jan 20 '26 15:01

kind user



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!