Nidheesh
Nidheesh

Reputation: 4562

Select boxes not getting displayed on iteration

Trying to get the select boxes through a loop. Only one item is getting displayed.

<table>
    <tbody id="addto_tb"></tbody>
</table>
var nodesList = ['node1','node2','node3'];
var select =  $('<select/>');

$('<option />', {value: 'node1', text: 'node1'}).appendTo(select);  
$('<option />', {value: 'node2', text: 'node2'}).appendTo(select);

$(nodesList).each(function(iter,elem){
    alert(elem);
    var trEle = $(document.createElement("tr"));
    trEle.addClass(" "+iter);

    var tdEle = $(document.createElement("td"));
    $(tdEle).append(select);

    trEle.append(tdEle);                            
    $('#addto_tb').append(trEle);
    $($($('#addto_tb').find("."+iter)).find('select')).val(elem);
});

In this case 3 select boxes should come. But Only one displays. When I put an alert, I can see all the three select boxes are coming but only one is getting displayed. When I inspect, I can see the first two <td>s are null.

Fiddle

Upvotes: 0

Views: 59

Answers (2)

SnyderJK
SnyderJK

Reputation: 80

When you create select, there is only one instance of that, so each loop, you actually end up just moving it to the next tr

Add the .clone() method for appending the item.

$(tdEle).append(select.clone());

Upvotes: 3

ADyson
ADyson

Reputation: 61914

Your loop is just moving the select element from one td to the next. You're referencing the same select every time (via a variable), so when you run $(tdEle).append(select); you're taking that select (the element referenced by your variable) from its current location and appending it to a new location. You need to declare a new, separate select item for each iteration of the loop:

var nodesList = ['node1','node2','node3'];

$(nodesList).each(function(iter,elem){
  alert(elem);
  var select =  $('<select/>');
  $('<option />', {value: 'node1', text: 'node1'}).appendTo(select);  
  $('<option />', {value: 'node2', text: 'node2'}).appendTo(select);
  var trEle = $(document.createElement("tr"));
  trEle.addClass(" "+iter);

  var tdEle = $(document.createElement("td"));
  $(tdEle).append(select);

  trEle.append(tdEle);                            
  $('#addto_tb').append(trEle);
  $($($('#addto_tb').find("."+iter)).find('select')).val(elem);
});

Upvotes: 0

Related Questions