Skip to content Skip to sidebar Skip to footer

Adding Onclick Event To Html Select Option

I added onclick event to my select tag like in the following code - but it does not work.... How can I set the opti

Solution 1:

Try it in the onchange handler:

functioncheckAlert(evt) {
  if (evt.target.value === "Say Hello") {
    alert('Hello');
  }
}
<selectonchange="checkAlert(event)"><option>Test</option><option>Say Hello</option></select>

Solution 2:

I prefer using Ids to add event listener to separate your code from html so I add an Id to your select tag with "my-select" for example and select this tag by its Id and add onchange event listener. This is the code:

<selectid="my-select"><optionvalue="1">Say Hello</option></select><script>document.getElementById("my-select").addEventListener("change", printMsg);
functionprintMsg() {
    alert("Hello");
}
</script>

Solution 3:

you should use onchange event on the select element itself.

<select onchange="alert('hello')">
    <option value="0">Say Hello</option>
    <option value="1">Some other option</option>
</select>

hope that helps,

Post a Comment for "Adding Onclick Event To Html Select Option"