Removing a Select Option in IE using jQuery

I have a selection list, that once selected I would like to remove or disable the option choosen. However, at a later time I may want to add or enable it again.

There is a bug in Internet Explorer that does not allow you to use the .hide() method on an option. It works just find in other browsers of course.

Searching Google I’ve determined that if I want it hidden in IE, that I would have to use the .remove() method, which removes it from the DOM, store it in an array, and add it back in when needed. I thought this was overkill.

So I found a good solution. The attribute ‘disabled’ works in IE. Since the hide() method will silently fail, do both. Therefore the option will just not be choosable in IE, and it will disapear in other browsers.

<select>
<option value="">Select One</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<a href="javascript:void(0);">add</a>
<script type="text/javascript">
//do this when the add link is clicked
$('a').click(function() {
//hide or disable the option
$('select :selected').attr('disabled','disabled').hide();
//reset the options back to the top
$('select').val('');
});
</script>

 

Advertisements