0

I'm trying to run a function when an option is clicked in a select dropdown menu. I tried the onChange event (inline html)...it's working but only runs the function when I change for another option (I know that's what onChange does). But what I need is that when someone clicks on the option, the function runs right away.

That's my html code:

<select id="Bname" onchange="updateClicked()" name="Bname"></select>

So like I said, the function is working correctly, and the onchange event works, but I need something that would trigger the function as soon as the option is clicked inside the select menu.

Thanks

Danimp
  • 99
  • 1
  • 8

1 Answers1

3

I think your doing it right, you wan't to listen to change.

<select id="Bname">
 <option value="volvo">Volvo</option>
 <option value="saab">Saab</option>
 <option value="mercedes">Mercedes</option>
 <option value="audi">Audi</option>
</select>

Then attach an event listener to it, and maybe check for the selected option to trigger a specific action for that option.

 var sel = document.getElementById('Bname');

 sel.addEventListener("change", myFunction);

 function myFunction() {

   if ( sel.value === 'volvo' ) {
     // Do stuff
   }

   console.log(sel.value);

 }
Tim
  • 1,680
  • 2
  • 15
  • 21