javascript - Inserting rows into table which rows are sorted by some value attribute -
i have simple html table , want insert new rows table jquery.
each row has custom val
attribute unix timestamp inside, example:
<tr data-val="1356998400"><!-- row content --></tr>
i want insert new rows jquery, , want them sorted val
attribute after insertion.
the obviuos solution set id
-s rows , manually scan rows array (performing time values comparison) before every single insertion find correct place insert, may there more jquery-like solution? guess kind of one-line solution should exist case.
initially, sort table basic sort
function (if rows haven't been sorted already):
markup
(note: added custom val
attribute data attribute)
<table> <tbody> <tr data-val="1"><td>1st</td></tr> <tr data-val="4"><td>3rd</td></tr> <tr data-val="7"><td>4th</td></tr> <tr data-val="2"><td>2nd</td></tr> </tbody> </table>
jquery
$('table').html(function() { return $(this).find('tr').sort(function(a, b) { return $(a).data('val') > $(b).data('val'); }); });
once rows have been sorted, can find position insert new row grabbing first row data-val
greater or equal data-val
of newrow
:
var $newrow = $('<tr data-val="3"><td>between 2nd , 3rd!</td></tr>'); var elementtoinsertbefore = $('tr').filter(function() { return $(this).data('val') >= $newrow.data('val'); }).get(0); if (typeof elementtoinsertbefore === 'undefined') { $('table').append($newrow); } else { $newrow.insertbefore(elementtoinsertbefore); }
so, if filter doesn't return elementtoinsertbefore
(ie. there no existing rows data-val
greater, or equal $newrow's
data-val
, append end of table, otherwise insert before elementtoinsertbefore
.
side note: it'd more efficient use for
loop elementtoinsertbefore
. way, find row meets criteria, can break
out, prevents further unecessary iterations (which could have decent performance gain when dealing large number of rows).
if want more elaborate, have @ jquery plugins mentioned.
Comments
Post a Comment