goJson
goJson

Reputation: 223

Binding an event handler to an HTML select.option

I want to show a warning message if a user selects a specific option, but the warning isn't appearing. How can I modify my code so that this works correctly? Here is a demo on jsFiddle which reproduces the problem?

HTML :

<input type="text" id="mail_address"/>
<select>
    <option value='google.com'>google.com</option>
    <option onClick="warningaa()" value=''>Don't send mail</option>
</select>

JS:

function warningaa() {
    alert('If you choose this option, you can not receive any information');
}

Upvotes: 10

Views: 20227

Answers (3)

Alex Char
Alex Char

Reputation: 33218

You can not use on click action in dropdown option. One solution is to use change on select element:

html

<input type="text" id="mail_address" />
<select onchange="warningaa(this);">
    <option value='google.com'>google.com</option>
    <option value='error'>error</option>
</select>

js

function warningaa(obj) {
    if(obj.value == "error") {
        alert('If you choose this option, you can not receive any infomation');
    }
}

fiddle

Upvotes: 10

Sebastien Daniel
Sebastien Daniel

Reputation: 4778

You need to set an event handler on the SELECT element, and watch the "value" of select, as below:

document.getElementById('mySelect').addEventListener('change', warn, true);
function warn(e) {
  e.preventDefault();
  e.stopPropagation();
  if (e.currentTarget.value === 'the value you want') {
    // do something
  } else {
  return;
}

The key here is using CHANGE event vs CLICK, since you want to react to a "change in value" and if that value = something, warn the user. using addEventListener is also a better approach overall, it clearly distinguishes your HTML from your JavaScript.

More on this here:

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener

and here:

https://developer.mozilla.org/en/docs/Web/API/Event

Upvotes: 1

Jesse Buitenhuis
Jesse Buitenhuis

Reputation: 670

The option tag does not support the onclick event. Use the onchange event on the select instead.

HTML

<input type="text" id="mail_address"/>
<select id="selectbox" onchange="warning(this)">
  <option value='google.com'>google.com</option>
  <option value='warning'>Do not send me any kind of shit</option>
</select>

JS

function warning(obj) {
  if(obj.value == 'warning') {
    alert('If you choose this option, you can not receive any infomation');
  }
}

Upvotes: 6

Related Questions