HTML:
<select id="dropdown">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
jQuery:
$("#dropdown").prepend("<option value='' selected='selected'></option>");
When I run this in FireFox or Chrome, the drop down has the newly inserted blank option selected. When I run it in IE8, it still has Volvo selected. Any ideas?
http://jsfiddle.net/YFu2h/
Method 1: Append the option tag to the select box The option to be added is created like a normal HTML string. The select box is selected with the jQuery selector and this option is added with the append() method. The append() method inserts the specified content as the last child of the jQuery collection.
Try: $("#dropdown"). prepend(new Option('', '', true, true)); $("#dropdown option:first"). attr("selected", "selected");
The option tag contains the value that would be used when selected. The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.
To detect real-time changes, you want the input event. document. addEventListener('input', function (event) { // Only run on our select menu if (event.target.id !== 'wizard') return; // Do stuff... }, false);
Change it to this, and it'll work:
$("#theSelectId").prepend("<option value=''></option>").val('');
http://jsfiddle.net/YFu2h/1/
It seems that IE only evaluates the selected
attribute when it first encounters the select
.
I'm not sure why your code is not working (maybe it has something to do with the fact that in IE, selectedIndex
is readonly) but, doing this works in IE:
$("#dropdown").prepend("<option value='' selected='selected'></option>");
$("#dropdown")[0].options[0].selected = true;
Try:
$("#dropdown").prepend(new Option('', '', true, true));
$("#dropdown option:first").attr("selected", "selected");
Or, if you prefer:
$("#dropdown").prepend("<option value=''></option>");
$("#dropdown option:first").attr("selected", "selected");
Using the first option is marginally quicker. The blank quotes mean blank value and blank text, so fill them in as you need. You don't need the selected attribute in the prepend now we are adding them afterwards. It's something to do with internet explorer not recognizing it being marked as selected as it has only just been created.
$("#id").prepend("<option value=' ' selected='selected'></option>");
prepend will add the option to top and selected='selected' will make it selected. As value=' ', so, it is blank value option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With