Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript : checking boolean values

Tags:

javascript

I have a boolean value set as a hidden variable in the form and I have the below javascript .

         $().ready(function() {

             var flag =  $('#popUpFlag').val();

             alert("flag = "+flag);

             if(flag){
                alert("flag is true");
             }else{
                alert("flag is false");
             }
        })

These are the outputs for the alert .

         flag =
         flag is false


         flag = false
         flag is false


         flag = true
         flag is false

My concern is obviously the third output . When the flag is true , why is it printing "flag is false" , instead of "flag is true" . I tested it in IE8 and FF 4

Suggestions are welcome.

like image 702
Vinoth Kumar C M Avatar asked Apr 27 '11 07:04

Vinoth Kumar C M


2 Answers

No, you don't have a boolean value in the hidden field. The value in the field is always a string.

When you use the string value as if it was a boolean value, you get unexpected results. A condition is false if the value is false, 0, "" or null, but the string "false" is neither, so it's evaluated as true.

If you want a boolean value, you have to parse the string. An easy way is to simply check if the string has a specific value:

var flag =  $('#popUpFlag').val() === 'true';
like image 126
Guffa Avatar answered Nov 06 '22 11:11

Guffa


flag is a string, so have this instead:

if (flag === "true") {
  //true
}
else if (flag === "false") {
  //false
}
like image 25
Shadow Wizard Hates Omicron Avatar answered Nov 06 '22 11:11

Shadow Wizard Hates Omicron