How To Insert OPTIONs into SELECT with jQuery -- Cross-Platform, Even IE6

Volomike picture Volomike · Jul 22, 2010 · Viewed 49k times · Source

I need a cross-platform way to insert OPTIONs into a SELECT with jQuery. I think I recall in the past that IE6 does nothing when this is called:

<select id="myselect" size="1">
<option value=""></option>
</select>
<script type="text/javascript">
$('#myselect').append('<option value="test1">test1</option>');
$('#myselect').append('<option value="test2">test2</option>');
</script>

I think I recall that the above worked in all browsers as well as Firefox 2+ and IE7+, but not IE6. Correct? If so, what's the workaround?

Answer

KP. picture KP. · Jul 22, 2010

First off, you aren't waiting for the DOM to be ready with your code. You should be wrapping your jQuery code in:

$(document).ready(function() {

    $('#myselect').append('<option value="test1">test1</option>');
    $('#myselect').append('<option value="test2">test2</option>');

});

I'm not sure about IE6 compatibility, but you could try the .appendTo function instead, such as:

$('<option value="Test3">Test 3</option>').appendTo("#myselect");

example:

http://jsfiddle.net/W6L9d/