302

As the question says, how do I add a new option to a DropDownList using jQuery?

Thanks

Earlz
  • 62,085
  • 98
  • 303
  • 499
flesh
  • 23,725
  • 24
  • 80
  • 97

12 Answers12

461

Without using any extra plugins,

var myOptions = {
    val1 : 'text1',
    val2 : 'text2'
};
var mySelect = $('#mySelect');
$.each(myOptions, function(val, text) {
    mySelect.append(
        $('<option></option>').val(val).html(text)
    );
});

If you had lots of options, or this code needed to be run very frequently, then you should look into using a DocumentFragment instead of modifying the DOM many times unnecessarily. For only a handful of options, I'd say it's not worth it though.

------------------------------- Added --------------------------------

DocumentFragment is good option for speed enhancement, but we cannot create option element using document.createElement('option') since IE6 and IE7 are not supporting it.

What we can do is, create a new select element and then append all options. Once loop is finished, append it to actual DOM object.

var myOptions = {
    val1 : 'text1',
    val2 : 'text2'
};
var _select = $('<select>');
$.each(myOptions, function(val, text) {
    _select.append(
            $('<option></option>').val(val).html(text)
        );
});
$('#mySelect').append(_select.html());

This way we'll modify DOM for only one time!

Vikas
  • 24,082
  • 37
  • 117
  • 159
nickf
  • 537,072
  • 198
  • 649
  • 721
  • 9
    The method parameters are a bit misleading, the function(val, text) should be function(index, option) for example. Works well otherwise. – mbillard Jul 01 '10 at 20:15
  • 15
    @Crossbrowser: I disagree - `val` and `text` actually describe the variables and their use. – nickf Jul 03 '10 at 00:34
  • 1
    for that example only, however as a general purpose method, those variables are misleading (it gave me no clue how to use that method). However, I'll give that the answer was not about the use of the $.each method. – mbillard Jul 03 '10 at 02:20
  • You are touching the DOM on each run of the loop. Better is to use a document fragment or at least a concatenated string and touch the DOM once. – Francisc Apr 23 '12 at 11:08
  • Not to mention you are asking jQuery to look for `#mySelect` on each run. Cache it to a local var please. – Francisc Apr 23 '12 at 11:08
  • Just make sure text is actually ""+text. I encountered a problem getting data with space from a database. – Sydwell Aug 17 '12 at 13:40
  • 1
    I was previously using `mySelect.append(new Option(text, val));`, which did not work in IE8. I had to switch to @nickf's `mySelect.append($('').val(val).html(text));` – Matthew Clark Oct 09 '12 at 20:30
  • is there a way to use this and also force the selected attribute to an option? i thought .val() would do this, but it doesn't seem to to in ie8. – BReal14 Jul 16 '13 at 20:42
  • 5
    @briansol : `.attr('selected', true|false)` – nickf Jul 16 '13 at 22:34
  • Excellent example as it can be populated using a dictionary object which is a very common scenario. I do agree with mbillard that the use of val and text which are very commonly used in JQuery as methods could be renamed to something more descriptive. – Remy Jul 30 '13 at 19:35
  • The second solution listed, for me, actually took almost twice as long as the first on large dropdowns. – Cymbals Sep 24 '15 at 20:56
173

With no plug-ins, this can be easier without using as much jQuery, instead going slightly more old-school:

var myOptions = {
    val1 : 'text1',
    val2 : 'text2'
};
$.each(myOptions, function(val, text) {
    $('#mySelect').append( new Option(text,val) );
});

If you want to specify whether or not the option a) is the default selected value, and b) should be selected now, you can pass in two more parameters:

    var defaultSelected = false;
    var nowSelected     = true;
    $('#mySelect').append( new Option(text,val,defaultSelected,nowSelected) );
Phrogz
  • 296,393
  • 112
  • 651
  • 745
14

With the plugin: jQuery Selection Box. You can do this:

var myOptions = {
        "Value 1" : "Text 1",
        "Value 2" : "Text 2",
        "Value 3" : "Text 3"
    }
    $("#myselect2").addOption(myOptions, false); 
Jon Winstanley
  • 23,010
  • 22
  • 73
  • 116
cgreeno
  • 31,943
  • 7
  • 66
  • 87
13

You may want to clear your DropDown first $('#DropDownQuality').empty();

I had my controller in MVC return a select list with only one item.

$('#DropDownQuality').append(
        $('<option></option>').val(data[0].Value).html(data[0].Text));    
Har
  • 4,864
  • 2
  • 19
  • 22
8

Add item to list in the begining

$("#ddlList").prepend('<option selected="selected" value="0"> Select </option>');

Add item to list in the end

$('<option value="6">Java Script</option>').appendTo("#ddlList");

Common Dropdown operation (Get, Set, Add, Remove) using jQuery

Zakaria
  • 983
  • 15
  • 24
  • 1
    If you use double-quotes inside your option parameters they will close the function and break the script. Changing `.prepend("...") / $("...")` to `.prepend('...') / $('...')` would fix the snippet. – Heraldmonkey Feb 02 '16 at 14:09
4

Pease note @Phrogz's solution doesn't work in IE 8 while @nickf's works in all major browsers. Another approach is:

$.each(myOptions, function(val, text) {
    $("#mySelect").append($("&lt;option/&gt;").attr("value", val).text(text));
});
Marshal
  • 4,452
  • 1
  • 23
  • 15
3

U can use direct

$"(.ddlClassName").Html("<option selected=\"selected\" value=\"1\">1</option><option value=\"2\">2</option>")

-> Here u can use direct string

Jay
  • 39
  • 1
3

And also, use .prepend() to add the option to the start of the options list. http://api.jquery.com/prepend/

Johan
  • 2,472
  • 1
  • 23
  • 25
0

using jquery you can use

      this.$('select#myid').append('<option>newvalue</option>');

where "myid" is the id of the dropdown list and newvalue is the text that you want to insert..

chopss
  • 771
  • 9
  • 19
0

I needed to add as many options to dropdowns as there were dropdowns on my page. So I used it in this way:

function myAppender(obj, value, text){
    obj.append($('<option></option>').val(value).html(text));
}

$(document).ready(function() {
    var counter = 0;
    var builder = 0;
    // Get the number of dropdowns
    $('[id*="ddlPosition_"]').each(function() {
        counter++;
    });

    // Add the options for each dropdown
    $('[id*="ddlPosition_"]').each(function() {
        var myId = this.id.split('_')[1];

        // Add each option in a loop for the specific dropdown we are on
        for (var i=0; i<counter; i++) {
            myAppender($('[id*="ddlPosition_'+myId+'"]'), i, i+1);
        }
        $('[id*="ddlPosition_'+myId+'"]').val(builder);
        builder++;
    });
});

This dynamically set up dropdowns with values like 1 to n, and automatically selected the value for the order that dropdown was in (i.e. 2nd dropdown got "2" in the box, etc.).

It was ridiculous that I could not use this or this.Object or $.obj or anything like that in my 2nd .each(), though --- I actually had to get the specific ID of that object and then grab and pass that whole object to my function before it would append. Fortunately the ID of my dropdown was separated by a "_" and I could grab it. I don't feel I should have had to, but it kept giving me jQuery exceptions otherwise. Something others struggling with what I was might enjoy knowing.

vapcguy
  • 7,097
  • 1
  • 56
  • 52
  • Why are you incrementing the counter in each? Are you new to jquery? var counter = $('[id*="ddlPosition_"]').length is less verbose and more efficient. I think you need a little more experience before you start posting your code. This is not production quality code as it is poorly written and overly complex for such a trivial task. No offense but there is a reason you have 58 answers and no up votes. – Athens Holloway Dec 06 '14 at 02:53
  • You obviously misunderstood what I was creating. The counter is to increment the value posted in the drop down, and I had several with the same ID, just with a different "_##" on the end, so .length() would've been inaccurate. That's the reason for the "id*=" in the selector. – vapcguy Dec 07 '14 at 15:31
  • As for my other answers, generally I advocate for simpler methods whenever possible, too, and if people weren't so esoteric with their coding and wrote things that were more simplified, my answers would probably have more votes. But people want to make themselves look smart and so they won't pick something so simple. Doesn't make me wrong for wanting to simply the industry. I don't enjoy troubleshooting or building onto other people's code that is ridiculously more complex than it needs to be, either. – vapcguy Dec 07 '14 at 15:38
  • I also might have more confidence in $(this).length() in that loop more if someone could explain why sending "$(this)" instead of the object to myAppender didn't work. – vapcguy Dec 07 '14 at 15:47
0

Lets think your response is "successData". This contains a list which you need to add as options in a dropdown menu.

success: function (successData) {
var sizeOfData = successData.length;
if (sizeOfData == 0) {
    //    NO DATA, throw an alert ...
    alert ("No Data Found");
} else {
    $.each(successData, function(val, text) {
        mySelect.append(
            $('<option></option>').val(val).html(text)
        );
    });
} }

This would work for you ....

Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
-1

try this Function:

function addtoselect(param,value){
    $('#mySelectBox').append('&lt;option value='+value+'&gt;'+param+'&lt;/option&gt;');
}
LoveAndCoding
  • 7,857
  • 2
  • 31
  • 55