Asked  7 Months ago    Answers:  5   Viewed   35 times

What's the easiest way to add an option to a dropdown using jQuery?

Will this work?

$("#mySelect").append('<option value=1>My option</option>');

 Answers

81

This did NOT work in IE8 (yet did in FF):

$("#selectList").append(new Option("option text", "value"));

This DID work:

var o = new Option("option text", "value");
/// jquerify the DOM object 'o' so we can use the html method
$(o).html("option text");
$("#selectList").append(o);
Tuesday, June 1, 2021
 
koenHuybrechts
answered 7 Months ago
59

Use:

$("#id option").each(function()
{
    // Add $(this).val() to your list
});

.each() | jQuery API Documentation

Tuesday, June 1, 2021
 
hakre
answered 7 Months ago
15

Try this:

$(".ct option[value='X']").each(function() {
    $(this).remove();
});

Or to be more terse, this will work just as well:

$(".ct option[value='X']").remove();
Thursday, June 3, 2021
 
huhushow
answered 7 Months ago
88

Doing a little digging, I can see this issue raised on GitHub.

One option is to check to see if the value exists, and append it if it doesn't.

var s2 = $("#selectEvents").select2({
    placeholder: "Choose event type",
    tags: true
});

var vals = ["Trade Fair", "CA", "Party"];

vals.forEach(function(e){
if(!s2.find('option:contains(' + e + ')').length) 
  s2.append($('<option>').text(e));
});

s2.val(vals).trigger("change"); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css" rel="stylesheet"/>

<select multiple name="event_type[]" class="form-control" id="selectEvents">
  <option>Trade Fair</option>
  <option>Party</option>
  <option>Foo</option>
  <option>Bar</option>
</select>
Tuesday, August 3, 2021
 
Zulakis
answered 5 Months ago
64

adding context to the selector is much faster than refining your selector

This is true in the general case. With respect to your specific examples however it is not necessarily true for jQuery <= 1.2.6.

Up to and including jQuery 1.2.6 the selector engine worked in a "top down" (or "left to right") manner. Meaning that both your examples would operate like this (roughly):

var root = document.getElementById('bar');
return root.getElementsByTagName('li');

jQuery 1.3.x (ie, Sizzle, which jQuery embeds) introduced a "bottom up" (or "right to left") approach to querying the DOM. So $('#bar li') now becomes (roughly):

var results = [];
var elements = document.getElementsByTagName('li');
for(var i=0; i < elements.length; i++) {
    var element = elements[i];
    var parent = element.parentNode;
    while(parent) {
        if(parent.id == 'bar') {
            results.push(element)
            break;
        }
        parent = parent.parentNode;
    }
}
return results

There are benefits and downsides to both approaches. You found one of the downsides.

Edit: just found out from this discussion that Sizzle trunk now makes a special exemption of selectors where #id is first. It uses that as the root context, speeding things up a bit. This should diminish if not eliminate the speed differences you are seeing.

Tuesday, August 10, 2021
 
Nil
answered 4 Months ago
Nil
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share