[jquery] How do I add options to a DropDownList using jQuery?

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

Thanks

This question is related to jquery user-interface drop-down-menu

The answer is


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($("<option/>").attr("value", val).text(text));
});

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.


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


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 ....


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));    

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); 

try this Function:

function addtoselect(param,value){
    $('#mySelectBox').append('&lt;option value='+value+'&gt;'+param+'&lt;/option&gt;');
}

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..


U can use direct

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

-> Here u can use direct string


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));
});

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


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); 

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));    

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


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..


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); 

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 ....


U can use direct

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

-> Here u can use direct string


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.


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) );

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


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) );

try this Function:

function addtoselect(param,value){
    $('#mySelectBox').append('&lt;option value='+value+'&gt;'+param+'&lt;/option&gt;');
}

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to user-interface

Calling another method java GUI How do I center text vertically and horizontally in Flutter? Is it possible to put a ConstraintLayout inside a ScrollView? How to change color of the back arrow in the new material theme? How to create RecyclerView with multiple view type? Android RecyclerView addition & removal of items tkinter: how to use after method Presenting a UIAlertController properly on an iPad using iOS 8 Android ViewPager with bottom dots How do I get the height and width of the Android Navigation Bar programmatically? How to implement drop down list in flutter? How can I create a dropdown menu from a List in Tkinter? How can I close a dropdown on click outside? Making a drop down list using swift? HTML: Select multiple as dropdown How to get selected value of a dropdown menu in ReactJS Avoid dropdown menu close on click inside Bootstrap 3 dropdown select How to make a drop down list in yii2? Android custom dropdown/popup menu