Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Adding td element to a tr

Using a row variable to get data dynamically and set the table row.

var row = '<tr>'+
      '<td>'+obj.Message+'</td>'+
      '<td>'+obj.Error+'</td>'+
      '<td>'+obj.Detail+'</td>'+
      '</tr>';

Based a value I tried to add another <td> to the row object but it didn't work.

if(obj.Type=='Error') {
  $(row).find('td:last').append('<td>'+ obj.ErrorCode+'</td>');
}
$('table> tbody:last').append(row);

First I tried to just append the <td> to row but that didn't work as well.

$(row).append('<td>'+ obj.ErrorCode+'</td>');
like image 932
Himanshu Yadav Avatar asked Oct 31 '13 15:10

Himanshu Yadav


2 Answers

You're not storing the last row.

When you call $(row).find(...).append(...) the result is not being stored in a variable. The best solution is probably keeping a jQuery object from the start:

//         v--- use a jQuery object here
var $row = $('<tr>'+
      '<td>'+obj.Message+'</td>'+
      '<td>'+obj.Error+'</td>'+
      '<td>'+obj.Detail+'</td>'+
      '</tr>');    
if(obj.Type=='Error') {
    $row.append('<td>'+ obj.ErrorCode+'</td>');
}
$('table> tbody:last').append($row);

See fiddle

like image 165
azz Avatar answered Oct 24 '22 11:10

azz


Instead of append use after and use === (or ==) instead of =

  if(obj.Type === 'Error') {
    $(row).find('td:last').after('<td>'+ obj.ErrorCode+'</td>'); //This will add the new td after the last one
   ..

or just append it to the row:

   $(row).append('<td>'+ obj.ErrorCode +'</td>'); //this will do the same thing, less code and append this as last td of your row.
like image 26
PSL Avatar answered Oct 24 '22 10:10

PSL