
Question:
I'm looking to dynamically populate a select element with names of items that are stored into an array.
For some reason it's not working and I'm not sure why.
<strong>HTML:</strong>
<div class="col-md-4 col-md-offset-4">
<select class="select1">
</select>
and
<select class="select2">
</select>
</div>
Note that I'm using bootstrap for layout.
Here's the jquery I'm using to try and populate ".select1"
<strong>JQUERY:</strong>
select: function() {
$.each(state.greens, function(index, value) {
$(".select1").append("<option value =' " + index + " '>" + state.greens[index].name + "</option>");
});
}
Note that the function 'select' is stored within an object called 'display'.
state.greens is the name of the array I'm trying to access.
So at the end of my html page I call display.select(); to call the function.
No error messages are showing up in the console.
Also, I saw this question: <a href="https://stackoverflow.com/questions/12926558/appending-options-to-select-using-jquery-doesnt-work" rel="nofollow">Appending options to select using jQuery doesn't work</a>
but was looking for a jquery centric answer and this seems like it ought to work.
Answer1:You can do in that way:
$.each(state.greens, function(index, value) {
$('.select1').append($('<option>', {
value: index ,
text: state.greens[index].name
}));
});
Answer2:When you append you are basically adding to the .innerHTML value of a container. This works for most elements except for <select>
. You'll have to add elements properly for the DOM to pick it up:
var select=document.getElementById('select1');
var option=document.createElement('option');
option.setAttribute('value','option1');
option.innerHTML='Option 1';
select.appendChild(option);