What is the best method for adding options to a select from a JSON object using jQuery?
I'm looking for something that I don't need a plugin to do, but would also be interested in the plugins that are out there.
This is what I did:
selectValues = {"1":"test 1","2":"test 2"};
for (key in selectValues) {
if (typeof(selectValues[key] == 'string') {
$('#mySelect').append('<option value="' + key + '">' + selectValues[key] + '</option>');
}
}
A clean/simple solution:
This is a cleaned up and simplified version of matdumsa's :
$.each(selectValues, function(key, value) {
$('#mySelect')
.append($('<option>', { value : key })
.text(value));
});
Changes from matdumsa's: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().
Source: Tips4all
Same as other answers, in jQuery fashion:
ReplyDelete$.each(selectValues, function(key, value) {
$('#mySelect')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
var output = [];
ReplyDelete$.each(selectValues, function(key, value)
{
output.push('<option value="'+ key +'">'+ value +'</option>');
});
$('#mySelect').html(output.join(''));
In this way you "touch the DOM" only one time.
I'm not sure if the latest line can be converted into $('#mySelect').html(output.join('')) because I don't know jquery internals (maybe it does some parsing in the html() method)
This should be like an answer, but it is slightly faster and cleaner.
ReplyDelete$.each(selectValues, function(key, value)
{
$('#mySelect').append($("<option/>", {
value: key,
text: value
}));
});
Using DOM Elements Creator plugin (my favorite):
ReplyDelete$.create('option', {'value': 'val'}, 'myText').appendTo('#mySelect');
Using the Option constructor (not sure about browser support):
$(new Option('myText', 'val')).appendTo('#mySelect');
Using document.createElement (avoiding extra work parsing HTML with $("<option></option>")):
$('#mySelect').append($(document.createElement("option")).
attr("value","val").text("myText"));
This looks nicer, provides readability, but is slower than other methods.
ReplyDelete$.each(selectData, function(i, option)
{
$("<option/>").val(option.id).text(option.title).appendTo("#selectBox");
});
If you want speed, the fastest (tested!) way is this, using array, not string concatenation, and using only one append call.
auxArr = [];
$.each(selectData, function(i, option)
{
auxArr[i] = "<option value='" + option.id + "'>" + option.title + "</option>";
});
$('#selectBox').append(auxArr.join(''));
jQuery
ReplyDeletevar list = $("#selectList");
$.each(items, function(index, item) {
list.append(new Option(item.text, item.value));
});
pure javascript
var list = document.getElementById("selectList");
for(var i in items) {
list.add(new Option(items[i].text, items[i].value));
}
var output = [];
ReplyDeletevar length = data.length;
for(var i=0; i < length; i++)
{
output[i++] = '<option value="'+ data[i].start +'">'+ data[i].start +'</option>';
}
$('#choose_schedule').get(0).innerHTML = output.join('');
I've done a few tests and this is, I believe does the job the fastest :P
Be forwarned... I am using jQuery Mobile 1.0b2 with PhoneGap 1.0.0 on an Android 2.2 (Cyanogen 7.0.1) phone (T-Mobile G2) and could not get the .append() method to work at all. I had to use .html() like follows:
ReplyDeletevar options;
$.each(data, function(index, object) {
options += '<option value="' + object.id + '">' + object.stop + '</option>';
});
$('#selectMenu').html(options);
function populateDropdown(select, data) {
ReplyDeleteselect.html('');
$.each(data, function(id, option) {
select.append($('<option></option>').val(option.value).html(option.name));
});
}
It works well with jQuery 1.4.1.
For complete article for using dynamic lists with ASP.NET MVC & jQuery visit:
http://www.codecapers.com/post/Dynamic-Select-Lists-with-MVC-and-jQuery.aspx
simple way is
ReplyDelete$('#SelectId').html("<option value='0'>select </option><option value='1'>Laguna</option>");
There's an approach using the Microsoft Templating approach that's currently under proposal for inclusion into jQuery core. There's more power in using the templating so for the simplest scenario it may not be the best option. For more details see Scott Gu's post outlining the features.
ReplyDeleteFirst include the templating js file, available from github.
<script src="Scripts/jquery.tmpl.js" type="text/javascript" />
Next set-up a template
<script id="templateOptionItem" type="text/html">
<option value=\'{{= Value}}\'>{{= Text}}</option>
</script>
Then with your data call the .render() method
var someData = [
{ Text: "one", Value: "1" },
{ Text: "two", Value: "2" },
{ Text: "three", Value: "3"}];
$("#templateOptionItem").render(someData).appendTo("#mySelect");
I've blogged this approach in more detail.
You can just iterate over your json array with the following code
ReplyDelete$('<option/>').attr("value","someValue").text("Option1").appendTo("#my-select-id");
A compromise of sorts between the top two answers, in a "one-liner":
ReplyDelete$.fn.append.apply($('mySelect'),
$.map(selectValues, function(val, idx) {
return $("<option/>")
.val(val.key)
.text(val.value);
})
);
Builds up an array of Option elements using map and then appends them all to the Select at once by using apply to send each Option as a separate argument on the append function.
A jQuery plugin could be found here: http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/.
ReplyDeleteI have made something like this, loading a dropdown item via Ajax. The response above is also acceptable, but it is always good to have as little DOM modification as as possible for better performance.
ReplyDeleteSo rather than add each item inside a loop it is better to collect items within a loop and append it once it's completed.
$(data).each(function(){
... Collect items
})
Append it,
$('#select_id').append(items);
or even better
$('#select_id').html(items);