Onclick in select does not work in IE

A little new to javascript. This question may seem a little too silly, but I can’t understand it , why the following does not 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</option> </select> 

The warning does not appear in IE (I am using IE8). But it works in firefox !!!!!

+6
javascript select onclick
source share
3 answers

According to w3schools , the option tag supports the onclick attribute. I tried with the bottom of the trunk of IE6, and that doesn't seem to be the case.

The easiest way to do this:

 <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 need, but should be pretty close.

edits

This will require 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 advisable to wrap onchange in a function in the js file instead of embedding it in html.

+6
source share

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 the decision of Daniel Mendel is completely fair.

+5
source share

This is due to the fact that IE does not register a click event when a new option is selected in the selection field (guessing). Instead, you should use the onBlur event (and paste the code into your javascript instead) like this (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> 
+2
source share

All Articles