I have this code
var opt = $("select option:first");
opt.remove();
$("button").on("click", function() {
$("select").prepend(opt).val(1);
});
That works fine in some browser. But, of course, IE isn't one of them. In IE the combo ends with the two options, but the text is in blank (there is no selected option). I assume this is because the option is still not loaded into the DOM. I assume that because I can easily fix this problem using this code instead:
var opt = $("select option:first");
opt.remove();
$("button").on("click", function() {
$("select").prepend(opt);
setTimeout(function() {
$("select").val(1);
}, 1);
});
However, I would prefer something nicer. Any ideas?
Note: I'm not looking for performance in the selector or things like that. The posted code is just a reduced example, not my real script.
Method 1: Append the option tag to the select box 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. Hence the option is added to the select element.
The HTMLSelectElement type represents the <select> element. It has the add() method that dynamically adds an option to the <select> element and the remove() method that removes an option from the <select> element: add(option,existingOption) – adds a new <option> element to the <select> before an existing option.
To add icons in select option text we have to use the bootstrap-select plugin, which is a great plugin for customizing plain HTML select with some great customization options using bootstrap style. With this plugin, we can style the select element with only simple data attributes or initialize with Javascript.
To get the text of the selected option, we first need to find the selected option using the find() method and then use the text() method to get the option text. where selectBox is the value of the id attribute of the <select> HTML tag.
This seems to work on all browsers, though I have no idea why your original code failed in IE.
var opt = $("select option:first");
opt.detach();
$("button").on("click", function() {
$("select").prepend(opt).prop("selectedIndex", 0);
});
http://jsfiddle.net/tEUxg/5/
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