Onclick in select not working in IE
Am a bit new to javascript. This question might sound a bit too silly, but I'm not able to figure it out why the following doesn't work in IE and works in firefox..
<select multiple="multiple">
<option value="tx" onClick="alert('tx');">Texas</option>
<option value="ak" onClick="alert('ak');">Alaska</option>
<option value="ca" onClick="alert('ca');">California</option>
<option value="ws" onClick="alert('ws');">Washington</option>
<option value="tn" onClick="alert('tn');">Tennessee</op开发者_如何学Pythontion>
</select>
The alert doesn't come up in IE (I'm using IE8). But it works in firefox!!!!!
According to w3schools, the option tag does support an onclick attribute. I tried with with bottom of the barrel IE6 and this doesn't seem to be the case.
The simplest way to do this would be:
<select multiple="multiple" onchange="alert(this.value);">
<option value="tx">Texas</option>
<option value="ak">Alaska</option>
<option value="ca">California</option>
<option value="ws">Washington</option>
<option value="tn">Tennessee</option>
</select>
This is not exactly what you are after, but should be pretty close.
EDITS
It would just take more work:
<select multiple="multiple" onchange="
switch (this.value){
case 'tx': funcOne(); break;
case 'ak': funcTwo(); break;
etc...
}
">
<option value="tx">Texas</option>
<option value="ak">Alaska</option>
<option value="ca">California</option>
<option value="ws">Washington</option>
<option value="tn">Tennessee</option>
</select>
At this point it would be appropriate to wrap the onchange into a function in a js file instead of embedding it in the html.
I would use the onchange event:
<select multiple="multiple" onchange="alert(this.options[this.selectedIndex].value)">
<option value="tx">Texas</option>
<option value="ak">Alaska</option>
<option value="ca">California</option>
<option value="ws">Washington</option>
<option value="tn">Tennessee</option>
</select>
Although Daniel Mendel's solution is perfectly valid.
This is because IE doesn't register a click event when you select a new option in a select field (guessing). Instead, you should use the onBlur event (and put the code into your javascript instead) like so (assuming jQuery):
<script type='text/javascript'>
$(document).ready(function(){
$('select#state').bind('blur', function(){
alert(this.val());
});
});
</script>
<select id='state' multiple="multiple">
<option value="tx">Texas</option>
<option value="ak">Alaska</option>
<option value="ca">California</option>
<option value="ws">Washington</option>
<option value="tn">Tennessee</option>
</select>
精彩评论