I am getting back a huge crazy JSON from an API, and I am struggling with putting it inside a select box. So far I have this code:
$('#gaua').live('change', function () {
var dropDownValue = $(this).val();
$("#gaCell").html("<select>");
$.each(gaAccount, function(k, v) {
$.each(v, function(k1, v1) {
console.log("k1 "+k1+" "+dropDownValue);
if(k1 == dropDownValue) {
console.log("k1 is equal to dropDownValue");
$.each(v1, function(k2, v2) {
console.log("v1 "+v1+" k2 "+k2+" v2 "+v2);
$("#gaCell").append("<option value='"+v2+"'>"+k2+"</option>");
});
}
});
});
$("#gaCell").append("</select>");
console.log($("#gaCell").html());
});
When I look at the console I see this:
<select></select><option value="4434">Option 1</option><option value="43333380">Option 2</option><option value="3233223">Option 3</option> ...
Why is the <select></select> being appended initially? Should the opening tag be set, then the option values added and finally the closed select tag?
The code looks crap, but I need to get this working properly before I clean it up. Any advice would really help, thanks!
You need to construct your element first, before appending it.
When you call
$('#gaCell').html('<select>'), you’re telling jQuery to append a select element, including closing tag.Try this:
This way you build up the full select element including children before appending it.