Doug Molineux
Doug Molineux

Reputation: 12431

Append a row to a sorted table with jQuery

How can I add a row to a dynamically-generated table but have the id of the tr's numerically ordered?

For example:

<table id="myDataTable">
<tr id="5143">
 <td>Data Cell 1</td>
 <td>Data Cell 2</td>
</tr>
<tr id="5144">
 <td>Data Cell 1</td>
 <td>Data Cell 2</td>
</tr>
<tr id="5149">
 <td>Data Cell 1</td>
 <td>Data Cell 2</td>
</tr>
<tr id="5150">
 <td>Data Cell 1</td>
 <td>Data Cell 2</td>
</tr>
</table>

How could I add a tr with an id of 5145 so that it was below 5143 but above 5149? I would like a solution that doesn't involve a plugin, if that's possible

Upvotes: 3

Views: 2094

Answers (3)

Joseph Marikle
Joseph Marikle

Reputation: 78520

I would sort it... but idk if this is efficient or not

//arr is an array of the row id's
//row is the row being inserted
idx = arr.sort().indexOf(row.id) - 1;
$(row).insertAfter($("#myDataTable tr")[idx]) 

e.g.

http://jsfiddle.net/Dq37V/

Upvotes: 4

orolo
orolo

Reputation: 3951

You could loop through the tr's and compare; if it is larger then the current id, then add it.

Example:

$('#myDataTable tr').each(function(index, Element) {
    if (5145 > Number($(Element).attr('id'))) {
        $(Element).after('<tr id="5145"><td>Data Cell 1</td></tr>');
    }
});

Upvotes: 2

Fatih Donmez
Fatih Donmez

Reputation: 4347

You can use $('#myDataTable tr').each(function() { .. } for going through on table's tr then if you find to match just use jquery after function to add new row just after right tr `

Upvotes: 1

Related Questions