10

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.

4
  • 2
    Is this your only code? It should definitely not print flag is false. Are you doing anything else in between? Commented Apr 27, 2011 at 7:19
  • What this contain, string boolean?? $('#popUpFlag').val(); Commented Apr 27, 2011 at 7:19
  • As @alex and @Shadow pointed out, $('#popUpFlag').val() will return a string, and not a boolean value. Now, every non-empty string evaluates to true, also "false", but this does not explain your second case then. So you must be doing something else... Commented Apr 27, 2011 at 7:26
  • @Felix You are right. Something else is going on. Commented Apr 27, 2011 at 7:30

3 Answers 3

15

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';
Sign up to request clarification or add additional context in comments.

Comments

6

flag is a string, so have this instead:

if (flag === "true") {
  //true
}
else if (flag === "false") {
  //false
}

3 Comments

Even if flag is the string "true", it should alert flag is true. But it is worth pointing out that it is a string and not a boolean.
And also "false" should be truthy.
@alex: Good point. So the second case is correct either. The OP os probably doing something but vice versa or whatever.
0

Hmm... I suspect that the value you are using is a string, so you're seeing the value correctly in the alert, but not when it tries to look at it like a boolean.

How can I convert a string to boolean in JavaScript?

Just try ocnverting to boolean and see if it still gives you the same issue

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.