What is the best way to add options to a select from a JavaScript object with jQuery?
The same as other answers, in a jQuery fashion:
$.each(selectValues, function(key, value) {
$('#mySelect')
.append($("<option></option>")
.attr("value", key)
.text(value));
});
var output = [];
$.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 is slightly faster and cleaner.
var selectValues = {
"1": "test 1",
"2": "test 2"
};
var $mySelect = $('#mySelect');
//
$.each(selectValues, function(key, value) {
var $option = $("<option/>", {
value: key,
text: value
});
$mySelect.append($option);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="mySelect"></select>