Reputation: 4668
I would like to know how to capture events within the dropdown list when a user click on a "select" dropdown list. I would like for example to intercept events when different elements of list are on focus.
I tried to tie event listeners to the option elements of the list but they do not capture anything. See sample code here:
<select>
<option onfocus="alert('Hi there');">Foo</option>
<option>Bar</option>
</select>
Upvotes: 2
Views: 10026
Reputation: 1211
You would have catch the onchange event, and then test to see what the value changed to, something like this:
Updated: notice the onfocus event I added.
For more ideas, check here: Is there an onSelect event or equivalent for HTML <select>?
<script type="text/javascript">
function myDDLOnChangeEvent()
{
var selectedValue = document.getElementById('myDDL').value;
if(selectedValue == 'Foo')
{
//alert('Hi there');
//do stuff here - except for alerts
//if you put an alert here, it will fire the onfocus event again..
// ..after you click 'ok' in the alert box
}
}
</script>
<select id="myDDL" onchange="myDDLOnChangeEvent();" onfocus="this.selectedIndex = -1;">
<option>Foo</option>
<option>Bar</option>
</select>
Upvotes: 2
Reputation: 324620
You can't, <select>
is a replaced element and its children act only as data for it rather than actual child elements.
The best you can do is apply an onChange
event to the <select>
itself, then access this.options[this.selectedIndex]
to do stuff.
Upvotes: 4