Home > Enterprise >  how to check in jquery if something not defined
how to check in jquery if something not defined

Time:12-10

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

CodePudding user response:

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);
}

CodePudding user response:

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);
  • Related