0

I've tried everything and if anyone could explain why this JavaScript code is not causing the alert button to be shown when I press enter on the HTML input field, that would be greatly appreciated.

    document.getElementById("inp").addEventListener("keypress", clickedEnter, false);
    
    function clickedEnter(event){
        if(event.key == "Enter"){
            alert("true");
        }
    }
<input type = "text" class = "inp" id = "inp" placeholder="Add Item"> 
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • Are there errors in the console? Is it being called? `console.log(event.key);` – epascarello Jul 20 '21 at 16:53
  • 2
    I made it runnable in your question and it runs fine. So what is different between this code and your actual code? – epascarello Jul 20 '21 at 16:56
  • As @epascarello pointed out, this runs just fine. – Ankit Gupta Jul 20 '21 at 16:56
  • As a side note, the [`keypress` event](https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event) is deprecated (not that it's going away any time soon -- or really, ever) in favor of [`beforeinput`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/beforeinput_event) and [`keydown`](https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event). – T.J. Crowder Jul 20 '21 at 16:57
  • Ah yes, I moved the script to the end of the body tag and it works fine now. – Alex Broad Jul 20 '21 at 16:59
  • Always best to look in the browser console for errors. In this case, the error that would be there is something like "Cannot read property `addEventListener` of `null`", see the [linked question's answers](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) for details. Happy coding! – T.J. Crowder Jul 20 '21 at 17:00

1 Answers1

0

It works fine, I think you might have an issue if the DOM has not loaded before your javascript has run. In which case you can put your script at the end of the body or run the javascript after the DOM has loaded, for example:

window.addEventListener('DOMContentLoaded', (event) => {

  function clickedEnter(event){
      if(event.key == "Enter"){
          alert("true");
      }
  }
  
  document.getElementById("inp").addEventListener("keypress", clickedEnter, false);

});
<input type = "text" class = "inp" id = "inp" placeholder="Add Item">
Donal
  • 31,121
  • 10
  • 63
  • 72