Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add option to a select and select it

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.

like image 344
Diego Avatar asked Dec 11 '12 14:12

Diego


People also ask

How do I add options to select box?

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.

How do I add dynamic options to an existing selection?

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.

How do I add a select option icon?

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.

How do I get selected text option in select?

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.


1 Answers

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/

like image 180
James Montagne Avatar answered Sep 25 '22 12:09

James Montagne