Search code examples
javascriptevent-handlingejs

addEventListener "click" or any other event is not working in ejs file


I have a select tag in ejs file,

\\html
 <label for="script">Choose a script:</label>
    <select name="script" id="script">
      <option value="main">Main</option>
      <option value="main2">Main2</option>
    </select>

I want a function to execute as soon as the value of the select tag is changed, I tried the 'onchange' event and it didn't work, so I tried 'onclick', but then I realised the eventlistener isn't responding at all no matter whatever the event type is, here's the code in js file -

\\JS
document.getElementById('script').addEventListener('onchange', ()=>{
    console.log("registered")
  })

However, if I use 'click' instead of 'onclick' and 'change' instead of 'onchange' everything works fine. So is there any difference when 'on' prefix is used?


Solution

  • The event name doesn't begin with on, it's just change or click.

    on is add at the beginning when you're creating the listener using an inline attribute in the HTML, e.g.

    <select name="script" id="script" onchange="console.log('registered')">
      <option value="main">Main</option>
      <option value="main2">Main2</option>
    </select>

    or when you're assigning it as a property:

    document.getElementById("script").onchange = function() {
      console.log('registered');
    };
    <select name="script" id="script">
      <option value="main">Main</option>
      <option value="main2">Main2</option>
    </select>