Suppose a list of options is available, how do you update the <select> with new <option>s?
Suppose a list of options is available, how do you update the <select> with new <option>s?
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.
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');