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’)
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">