2

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.

HTML:

<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"

JQUERY:

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: Appending options to select using jQuery doesn't work

but was looking for a jquery centric answer and this seems like it ought to work.

4
  • Is it possible state.greens is not within scope of your function? Try consoling state.greens.length on the first line of your function. I would also avoid naming your function 'select'. Commented Jul 14, 2015 at 1:05
  • 1
    Definitely your code works. See this fiddle.jshell.net/0z38v1bd ... as @RyanNeuffer said, make sure state.greens is in the same context of your select method Commented Jul 14, 2015 at 1:23
  • @RyanNeuffer - I followed your recommendation and the length of state.greens was 12.......which is what it should be. Any ideas? Commented Jul 14, 2015 at 11:47
  • The code works: jsfiddle.net/h5kuhL6x so there's something else going on that's not reflected in your example/setup. Console out $(".select1").length and ensure it exists in the DOM when you are calling display.select(); Commented Jul 14, 2015 at 13:46

2 Answers 2

3

You can do in that way:

$.each(state.greens, function(index, value) {
    $('.select1').append($('<option>', {
        value: index ,
        text: state.greens[index].name
    }));
});
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.