7

I added onclick event to my select tag like in the following code -

<option onclick="alert('Hello')">Say Hello</option>

but it does not work....

How can I set the option onclick event to fire ?

2
  • 4
    we don't have click event for option. use onchange event in select instead. Commented Jul 15, 2018 at 10:20
  • 1
    I couldn't comment because i don't have 50 reps. In my case i need onclick event for the option element because i need to focus on next text input on iOS Safari which only allows such thing by a user action (e.g user click). Commented Nov 23, 2022 at 10:25

3 Answers 3

13

Try it in the onchange handler:

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

Sign up to request clarification or add additional context in comments.

Comments

3

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:

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

Comments

0

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,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.