I'm trying to append values to a SELECT box, that gets dynamically added to the body of a page. A fiddle can be seen here: https://jsfiddle.net/mr2qtmw9/
HTML:
<body>
foo bar
</body>
JS:
var countries = new Object();
countries['AT'] = "Austria";
countries['AU'] = "Australia";
countries['BE'] = "Belgium";
countries['BG'] = "Bulgaria";
countries['CA'] = "Canada";
$(document).ready(function() {
$('body').append( "<select id='foo'></select>" );
// fill out the country, and its selected value
$.each(countries, function(i,x) {
$('#Country').append($('<option>', { value : i }).text(x));
});
});
The SELECT box gets created, and the $.each() runs through... but the option's don't get added.
What am I missing? (the same code works fine when the select box appears on the initial DOM... it just seems to have an issue when its dynamically injected)
UPDATE: Sorry, I put the wrong ID in the example! On the live script, the ID is "Country", and the selector is "#Country". It still doesn't work on my dev server (much more complex code), so I guess the issue must lie elsewhere :(
UPDATE 2: Doh, this was a big oversight on my part! (sometimes writing up and issue helps you to spot these). I put an alert() inside the function that was doing the work, and found it was running 2 times. Sure enough, after checking the code I found there was a 2nd place I was calling the same function. As such, it WAS adding the options, but to the 1st instance of the SELECT (and the 2nd one was overlapping, so I couldn't see the first one).
I have half a mind to delete this question, as it makes me look so dumb... but I think I'll leave it up, so hopefully it can help save someone else from a similar embarrassment ;)
$('#Country') !== $('#foo')