Reputation: 34227
Suppose a list of options is available, how do you update the <select>
with new <option>
s?
Upvotes: 324
Views: 425756
Reputation: 165069
If you have an array or object of option values / labels, an alternative to iterating each and using .append()
individually is to map to an array and call .append()
once
const optionsArray = [
{ value: 1, text: 'One' },
{ value: 2, text: 'Two' },
];
$('#array')
.empty()
.append(
optionsArray.map(({ value, text }) => $('<option>', { value, text })),
);
const optionsObject = {
Three: 3,
Four: 4,
};
$('#object')
.empty()
.append(
Object.entries(optionsObject).map(([text, value]) =>
$('<option>', { value, text }),
),
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.slim.min.js"></script>
<p>
<select id="array">
<option>Remove me</option>
</select>
</p>
<p>
<select id="object">
<option>Remove me</option>
</select>
</p>
Upvotes: 0
Reputation: 514
Most approaches start by deleting all the existing options and re-populating the dropdown. However, I prefer to add and remove individual options to avoid altering the current selection, if any.
<option></option>
<option value="12151d81-fe94-4007-8f1f-907aa8129d0a" data-text="Scrambled Eggs">Scrambled Eggs</option>
This example assumes that the options HTML is structured like the above. options
is JSON data like the following:
{
"guid": "bf42ba25-02b3-4d49-b4cf-02467c4fc44d",
"value": "Granola"
},
{
"guid": "89004730-bb92-4cd6-986a-28e228a94d54",
"value": "Yogurt"
}
field
is the input object.
function update_options(field, options) {
// If item doesn't exist in dropdown, add it.
$.each(options, function (index, item) {
if (field.find(`option[value="${item.guid}"]`).length == 0) {
$(`<option value="${item.guid}" data-text="${item.value}">${item.value}<\/option>`).appendTo(field);
}
});
// If item in dropdown doesn't exist in data, remove it.
$.each(field.find('option'), function (index, item) {
if (options.find(x => x.guid == item.value) == undefined) {
field.find(`option[value="${item.value}"]`).remove();
}
});
}
Upvotes: 0
Reputation: 71
Old school of doing things by hand has always been good for me.
Clean the select and leave the first option:
$('#your_select_id').find('option').remove()
.end().append('<option value="0">Selec...</option>')
.val('whatever');
If your data comes from a Json or whatever (just Concat the data):
var JSONObject = JSON.parse(data);
newOptionsSelect = '';
for (var key in JSONObject) {
if (JSONObject.hasOwnProperty(key)) {
var newOptionsSelect = newOptionsSelect + '<option value="'+JSONObject[key]["value"]+'">'+JSONObject[key]["text"]+'</option>';
}
}
$('#your_select_id').append( newOptionsSelect );
My Json Objetc:
[{"value":1,"text":"Text 1"},{"value":2,"text":"Text 2"},{"value":3,"text":"Text 3"}]
This solution is ideal for working with Ajax, and answers in Json from a database.
Upvotes: 2
Reputation: 31
Does this help?
$("#SelectName option[value='theValueOfOption']")[0].selected = true;
Upvotes: 3
Reputation: 1724
if we update <select>
constantly and we need to save previous value :
var newOptions = {
'Option 1':'value-1',
'Option 2':'value-2'
};
var $el = $('#select');
var prevValue = $el.val();
$el.empty();
$.each(newOptions, function(key, value) {
$el.append($('<option></option>').attr('value', value).text(key));
if (value === prevValue){
$el.val(value);
}
});
$el.trigger('change');
Upvotes: 2
Reputation: 828170
You can remove the existing options by using the empty
method, and then add your new options:
var option = $('<option></option>').attr("value", "option value").text("Text");
$("#selectId").empty().append(option);
If you have your new options in an object you can:
var newOptions = {"Option 1": "value1",
"Option 2": "value2",
"Option 3": "value3"
};
var $el = $("#selectId");
$el.empty(); // remove old options
$.each(newOptions, function(key,value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
Edit: For removing the all the options but the first, you can use the :gt
selector, to get all the option
elements with index greater than zero and remove
them:
$('#selectId option:gt(0)').remove(); // remove all options, but not the first
Upvotes: 704
Reputation: 460
For some odd reason this part
$el.empty(); // remove old options
from CMS solution didn't work for me, so instead of that I've simply used this
el.html(' ');
And it's works. So my working code now looks like that:
var newOptions = {
"Option 1":"option-1",
"Option 2":"option-2"
};
var $el = $('.selectClass');
$el.html(' ');
$.each(newOptions, function(key, value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
Upvotes: 6
Reputation: 1463
Removing and adding DOM element is slower than modification of existing one.
If your option sets have same length, you may do something like this:
$('#my-select option')
.each(function(index) {
$(this).text('someNewText').val('someNewValue');
});
In case your new option set has different length, you may delete/add empty options you really need, using some technique described above.
Upvotes: 3
Reputation: 6300
If for example your html code contain this code:
<select id="selectId"><option>Test1</option><option>Test2</option></select>
In order to change the list of option inside your select, you can use this code bellow. when your name select named selectId.
var option = $('<option></option>').attr("value", "option value").text("Text");
$("#selectId").html(option);
in this example above i change the old list of option by only one new option.
Upvotes: 1
Reputation: 3595
I threw CMS's excellent answer into a quick jQuery extension:
(function($, window) {
$.fn.replaceOptions = function(options) {
var self, $option;
this.empty();
self = this;
$.each(options, function(index, option) {
$option = $("<option></option>")
.attr("value", option.value)
.text(option.text);
self.append($option);
});
};
})(jQuery, window);
It expects an array of objects which contain "text" and "value" keys. So usage is as follows:
var options = [
{text: "one", value: 1},
{text: "two", value: 2}
];
$("#foo").replaceOptions(options);
Upvotes: 86
Reputation: 187110
$('#comboBx').append($("<option></option>").attr("value",key).text(value));
where comboBx is your combo box id.
or you can append options as string to the already existing innerHTML and then assign to the select innerHTML.
Edit
If you need to keep the first option and remove all other then you can use
var firstOption = $("#cmb1 option:first-child");
$("#cmb1").empty().append(firstOption);
Upvotes: 21