Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery append html element to div after for loop, strange behaviour

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?

like image 673
Milos911 Avatar asked Jan 23 '12 09:01

Milos911


3 Answers

I believe that jQuery will generate the DOM like this:

<div id="date">
    <select id="date">
        <option value="0">- - SELECT - -</option>
    </select>
    <option value="">foo</option>
    <option value="">bar</option>
    etc...
</div>

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:

// dummy data object for example
var data = new Array(new Array(), new Array());
data[0].date_time = 2011;
data[1].date_time = 2012;

var options = new Array();
$.each(data, function(index, option) {
    options.push('<option value="' + index + '">'+ option.date_time +'</option>');
});

$('<select id="date"/>').append(options.join('')).appendTo('#date');

Assuming the existing HTML:

<div id="date"></div>

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

like image 173
andyb Avatar answered Oct 16 '22 03:10

andyb


It is not the right way to create html dynamically. You should create the complete markup all at once by putting it into an array and then provide it to jQuery. Try this

var html = [];
html.push('<select id="date">');
html.push('<option value="0">- - SELECT - -</option>');
for(var i in data){
   html.push('<option value="">'+data[i]['date_time']+'</option>');
}
html.push('</select>');
//This selector should be some container like dateContainer
//because you have already give date as id to the above select element
$('#dateContainer').html(html.join(''));
like image 45
ShankarSangoli Avatar answered Oct 16 '22 01:10

ShankarSangoli


$('#date').append($("<select/>", { name: "name"+i})
 .find('select')   
 .append($("<option/>", { value: "abc"+i}).text('cell'))   
 .append($("<option/>", { value: "abc"+i}).text('home'))   
 .append($("<option/>", { value: "abc"+i}).text('work'));

all options should wrap inside select

like image 2
Nitin Avatar answered Oct 16 '22 01:10

Nitin