Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript isset() function [duplicate]

Tags:

javascript

php

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";
    }
}
like image 652
dhiv Avatar asked Apr 24 '14 07:04

dhiv


3 Answers

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)

like image 67
AyB Avatar answered Nov 19 '22 00:11

AyB


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.
}
like image 34
Amit Joki Avatar answered Nov 19 '22 00:11

Amit Joki


    if(typeof(data.length) != 'undefined')
    {
       // do something
    }

    if(empty(data))
    {
        // do something
    }

   if(typeof(data) == 'undefined' || data === null)
   {
     //do something
   }
like image 2
Naresh Avatar answered Nov 19 '22 02:11

Naresh