Barium Scoorge
Barium Scoorge

Reputation: 2008

JQuery append stange behavior

I can't explain this .append() behavior...

var listTopic = $.parseJSON(data);
for(i = 0; i < listTopic.length ; i++)
{
     $('#idSelect').append('<option>').append(listTopic[i].name).append('</option>');
}

Output:

<option></option>
value1
<option></option>
value2

Upvotes: 2

Views: 47

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240878

It looks like the browser is automatically inserting closing/opening tags because of the partial tags you are inserting.

You could use the following instead:

var listTopic = $.parseJSON(data);
for(i = 0; i < listTopic.length ; i++) {
  $('#idSelect').append('<option>' + listTopic[i].name + '</option>');
}

Alternatively, you could also use:

var listTopic = $.parseJSON(data);
for(i = 0; i < listTopic.length ; i++) {
  $('#idSelect').append($('<option />').text(listTopic[i].name));
}

And if you want to set the value/text at the same time:

var listTopic = $.parseJSON(data);
for(i = 0; i < listTopic.length ; i++) {
  $('#idSelect').append($('<option />').val(listTopic[i].name).text(listTopic[i].name));
}

Upvotes: 2

Related Questions