Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

addEventListner , keypress event not working

Hi im trying to make is so that when you press enter while the focus is on input in javascript

However its not working but giving me this message:

X script.js:163 Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is the input:

<input type="search" id="in1" class="form-control">

Note: I’ using bootstrap

This is the code i tried:

document.getElementById("in1").addEventListener("keypress",callSearchDB);

This is the callSearchDB() function:

function callSearchDB(e) {
    console.log(e);
}

Why its not working

>Solution :

Try DOMContentLoaded so you can be sure that your HTML document is completely parsed before your JavaScript runs.

document.addEventListener("DOMContentLoaded", () => {
  document.getElementById("in1").addEventListener("keypress", callSearchDB);
});


function callSearchDB(e) {
  if (e.keycode === 13 || e.key === 'Enter') {
    console.log('entered')
  }
}
<input type="search" id="in1" class="form-control">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading