views:

39261

answers:

6

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

Thanks

+7  A: 

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); 
cgreeno
+1  A: 

I use this useful plugin

Andrew Bullock
+61  A: 

without using any extra plugins,

var myOptions = {
    val1 : 'text1',
    val2 : 'text2'
};
$.each(myOptions, function(val, text) {
    $('#mySelect').append(
        $('<option></option>').val(val).html(text)
    );
});
nickf
works like a charm :)
flesh
The method parameters are a bit misleading, the function(val, text) should be function(index, option) for example. Works well otherwise.
GoodEnough
@Crossbrowser: I disagree - `val` and `text` actually describe the variables and their use.
nickf
@nickf 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.
GoodEnough
+7  A: 

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) );
});
Phrogz
A: 

Worked!!I too found the naming convention a little confusing, although it works well for this example. Thanks though!

Sajjan Sarkar
A: 

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