Wednesday, September 30, 2009

[jQuery] Re: Getting Last ID

> What is the best method to get the last ID so I have
>
> 1
> 3
> 4

Here's my untested solution:

function addNewRow()
{
var $tbody = $("#list tbody:first");
var newId = +($tbody.find("tr:last").attr("id") || "0") + 1;
var $row = $("<tr />").attr("id", newId).appendTo($tbody);
...
}

If there are no rows in the table yet, the .attr will return undefined
and the || will use "0" instead. That will make the first row in the
table id="1".

However, an id attribute of all digits is not valid; it should start
with a letter.

http://www.w3.org/TR/html4/types.html#type-id

So a better way might be to define the row ids as row0, row1, etc and
do this:

var newNum = +($tbody.find("tr:last").attr("id") || "row0").substr
(3) + 1;
var $row = $("<tr />").attr("id", "row"+newNum).appendTo($tbody);

No comments: