Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if you're currently in the last row of an HTML table?

I have a keydown event that I'm using to add a blank row to a table. But I only want the new row to be added if the keydown event happens when the cursor is in last row of the table.

This is my current jQuery event. .glCreditValue is the class of an input textbox that resides in the last TD of the table row. So when the user tabs out of that input, IF the TD that the input is inside of is in the last row of the table, I want to add a new row.

Being that the table data is generated dynamically, every row's final TD has an input textbox with the class .glCreditValue.

$(".glCreditValue").keydown(function(event) {
        var keycode = event.keyCode;
        if (keycode == 9) {
            //HERE i would like to make sure that i'm in the last row of the table
            AddNewRow();
        }
    });

I'm trying to make use of the tr:last selector, but I'm not sure quite where to go from here.

like image 358
ghost_mv Avatar asked Dec 14 '10 21:12

ghost_mv


People also ask

How do I find the last row of a table?

To get the last record, the following is the query. mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1; The following is the output. The above output shows that we have fetched the last record, with Id 4 and Name Carol.

How to get table last row value in jQuery?

$("#TableId"). find("tr"). last();

How do you find a row in a table in HTML?

The <tr> HTML element defines a row of cells in a table.


2 Answers

There are a few ways to do this, for example you could check the .closest() parent <tr> and see if it .is() a :last-child, like this:

$(".glCreditValue").keydown(function(event) {
  if (event.which == 9 && $(this).closest("tr").is(":last-child")) {
      AddNewRow();
  }
});
like image 185
Nick Craver Avatar answered Oct 06 '22 00:10

Nick Craver


One way to do it without having the overhead of running a selector is to simply get the .closest() row, then go to the .next() element and test its .length property.

It will be 0 if you were on the last <tr>.

if( !$(this).closest('tr').next().length ) {
   // was the last row
}
like image 43
user113716 Avatar answered Oct 06 '22 01:10

user113716