0

I tried the following code to understand how i can get 0 if the value is not defined.

This below is my try to understand but I am getting same error as described below.

var tbl = $("#tableOccupation")[0] != 'undefined' ? $("#tableOccupation")[0] : 0;
alert(tbl.rows.length);

that if not undefined,

return 0 else return whatever the rows.length is

that is above my try but it is still showing

Uncaught TypeError: tbl is undefined

Notion
  • 54
  • 7
  • `const tbl = $("#tableOccupation"); console.log(tbl?.length ?? 0)` – mplungjan Dec 09 '21 at 16:43
  • Don't check for `undefined`, it's notoriously unreliable. Check `$("#tblId").length === 0`. See this answer for more details: [is there an exists function in jquery](https://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery). But in many cases you don't need to: `$("#tableOccupation tr").length` would give you what you want, 0 if there's no table and 0 if there's no rows in that table. – freedomn-m Dec 09 '21 at 16:53
  • Does this answer your question (though not directly asked this way): [is there an exists function in jquery](https://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery)? – freedomn-m Dec 09 '21 at 16:54

2 Answers2

0

Your error come from this :

var tbl = $("#tableOccupation")[0] != 'undefined' ? $("#tableOccupation")[0] : 0;

You should check for undefined like this ( by removing quotes surrounding undefined )

var tbl = $("#tableOccupation")[0] != undefined ? $("#tableOccupation")[0] : 0;

undefined is a type, not a string :

console.log(undefined == 'undefined') // Prints false

More cleaner solution would be to just check for undefined like this :

let tbl = $("#tableOccupation")[0];

if (tbl) {
  alert(tbl.rows.length);
}
Julien
  • 832
  • 7
  • 15
0

Given that the rows collection in a HTML Table element refers to every tr within that table, you can just do this:

let $tbl = $("#tableOccupation");
let numberOfRows = $tbl.find('tr').length;
console.log(numberOfRows);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339