Here is the code:
$('#date').append(
'<select id="date">'+
'<option value="0">- - SELECT - -</option>');
for(var i in data){
$('#date').append(
'<option value="">'+data[i]['date_time']+'</option>');
});
$('#date').append('</select>');
</select> is always added above for loop. If i replace it with just work select for example, it is appended at the end, where it should be. Why is this happening and how can i fix it?
I believe that jQuery will generate the DOM like this:
Since it is automatically closing the
<select>after the first.append(). What you are doing afterwards is appending the options to the<div id="#date"/>rather than the<select>that was appended. I don’t think the final closing</select>will actually do anything either.If you really want to use append the following JavaScript will add the options to the correct node:
Assuming the existing HTML:
However this does incur an overhead since appending is occurring twice. The faster approach is to build up the options markup as already answered by ShankarSangoli