Home » Jquery » Adding options to a <select> using jQuery?

Adding options to a <select> using jQuery?

Posted by: admin November 2, 2017 Leave a comment

Questions:

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:

Personally, I prefer this syntax for appending options:

$('#mySelect').append($('<option>', {
    value: 1,
    text: 'My option'
}));

If you’re adding options from a collection of items, you can do the following:

$.each(items, function (i, item) {
    $('#mySelect').append($('<option>', { 
        value: item.value,
        text : item.text 
    }));
});

Questions:
Answers:

I agree Ashish, 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);

Questions:
Answers:

You can add option using following syntax, Also you can visit to way handle option in jQuery for more details.

  1. $(‘select’).append($(”, {value:1, text:’One’}));

  2. $(‘select’).append(‘One’);

  3. var option = new Option(text, value); $(‘select’).append($(option));

Questions:
Answers:

If the option name or value is dynamic, you won’t want to have to worry about escaping special characters in it; in this you might prefer simple DOM methods:

var s= document.getElementById('mySelect');
s.options[s.options.length]= new Option('My option', '1');

Questions:
Answers:

Option 1-

You can try this-

$('#selectID').append($('<option>',
 {
    value: value_variable,
    text : text_variable
}));

Like this-

for (i = 0; i < 10; i++)
{ 
     $('#mySelect').append($('<option>',
     {
        value: i,
        text : "Option "+i 
    }));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id='mySelect'></select>

Option 2-

Or try this-

$('#selectID').append( '<option value="'+value_variable+'">'+text_variable+'</option>' );

Like this-

for (i = 0; i < 10; i++)
{ 
     $('#mySelect').append( '<option value="'+i+'">'+'Option '+i+'</option>' );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id='mySelect'></select>

Questions:
Answers:

for whatever reason doing $("#myselect").append(new Option("text", "text")); isn’t working for me in IE7+

I had to use $("#myselect").html("<option value='text'>text</option>");

Questions:
Answers:

That works well.

If adding more than one option element, I’d recommend performing the append once as opposed to performing an append on each element.

Questions:
Answers:

To help performance you should try to only alter the DOM once, even more so if you are adding many options.

var html = '';

for (var i = 0, len = data.length; i < len; ++i) {
    html.join('<option value="' + data[i]['value'] + '">' + data[i]['label'] + '</option>');
}           

$('#select').append(html);

Questions:
Answers:
$('#mySelect').empty().append('<option value=1>My option</option>').selectmenu('refresh');

Questions:
Answers:

I like to use non jquery approach:

mySelect.add(new Option('My option', 1));

If you want the option to be selected, it is just as simple as:

mySelect.add(new Option('My option', 1, true));   

Questions:
Answers:
var select = $('#myselect');
var newOptions = {
                'red' : 'Red',
                'blue' : 'Blue',
                'green' : 'Green',
                'yellow' : 'Yellow'
            };
$('option', select).remove();
$.each(newOptions, function(text, key) {
    var option = new Option(key, text);
    select.append($(option));
});

Questions:
Answers:

Not mentioned in any answer but useful is the case where you want that option to be also selected, you can add:

var o = new Option("option text", "value");
o.selected=true;
$("#mySelect").append(o);

Questions:
Answers:

You can add options dynamically into dropdown as shown in below example. Here in this example I have taken array data and binded those array value to dropdown as shown in output screenshot

Output:

enter image description here

var resultData=["Mumbai","Delhi","Chennai","Goa"]
$(document).ready(function(){
   var myselect = $('<select>');
     $.each(resultData, function(index, key) {
	     myselect.append( $('<option></option>').val(key).html(key) );
       });
      $('#selectCity').append(myselect.html());
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>

<select  id="selectCity">

</select>

Questions:
Answers:

You can append and set the Value attribute with text:

$("#id").append($('<option></option>').attr("value", '').text(''));
$("#id").append($('<option></option>').attr("value", '4').text('Financial Institutions'));

Questions:
Answers:

If you want to insert the new option at a specific index in the select:

$("#my_select option").eq(2).before($('<option>', {
    value: 'New Item',
    text: 'New Item'
}));

This will insert the “New Item” as the 3rd item in the select.

Questions:
Answers:

We found some problem when you append option and use jquery validate.
You must click one item in select multiple list.
You will add this code to handle:

$("#phonelist").append("<option value='"+ 'yournewvalue' +"' >"+ 'yournewvalue' +"</option>");

$("#phonelist option:selected").removeAttr("selected"); // add to remove lase selected

$('#phonelist option[value=' + 'yournewvalue' + ']').attr('selected', true); //add new selected

https://i.stack.imgur.com/HOjIY.png

Questions:
Answers:

if u have optgroup inside select, u got error in DOM.

I think a best way:

$("#select option:last").after($('<option value="1">my option</option>'));

Questions:
Answers:

U can try below code to append to option

  <select id="mySelect"></select>

    <script>
          $("#mySelect").append($("<option></option>").val("1").html("My enter code hereoption"));
    </script>