How to check isset
in javascript.
I have used in the following way.
var sessionvalue = document.getElementById('sessionvalue').value;
if(Here I have to check if isset the sessionvalue or not){
if(sessionvalue == "" || sessionvalue == null)
{
document.getElementById('sessionvalue').style.borderColor="red";
return false;
}
else
{
document.getElementById('sessionvalue').style.borderColor="#ccc";
}
}
When javascript variables are not declared and you try to call them, they return undefined
, so you can do:
if (typeof sessionvalue == "undefined" || sessionvalue == null)
You can just do:
if(sessionvalue)
The above will automatically check for undefined
, null
(And NaN
,false
,""
)
You can even make it a global function if you need it like you're used to in php.
function isset(_var){
return !!_var; // converting to boolean.
}
if(typeof(data.length) != 'undefined')
{
// do something
}
if(empty(data))
{
// do something
}
if(typeof(data) == 'undefined' || data === null)
{
//do something
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With