4

alert(x) is false. But for some reason it is not going into the if statement? Any ideas?

Html

 @{bool x = false;
            foreach (var c in Model.Cleaner.TimeConfirmations.Where(l => l.date.ToShortDateString() == DateTime.Now.ToShortDateString() || l.date.ToShortDateString() == DateTime.Now.AddDays(1).ToShortDateString()))
            {
                     x = true;
            }
            <span class="ifAvailable" data-confirmationchecker="@x" value="15">@x</span>
           }

Jquery

var x = $(".ifAvailable").data('confirmationchecker')
alert(x);
if ( x == false) {
    alert("hi")
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Newbie
  • 239
  • 2
  • 11

3 Answers3

6

Data attributes can only contain strings:

The data-* attributes consist of two parts:

  1. The attribute name should not contain any uppercase letters, and must be at least one character long after the prefix "data-"
  2. The attribute value can be any string

So you're comparing the string "false" to the Boolean false, which are not the same.

Instead of

if (x == false)

use

if (x == "false")

Or, you could use this technique:

var x = ($(".ifAvailable").data('confirmationchecker') == "true");
alert(x);
if ( x == false) {
    alert("hi")
}
Community
  • 1
  • 1
John Wu
  • 50,556
  • 8
  • 44
  • 80
1

Your x is a string, convert the value into a boolean and then do the check

var x = $(".ifAvailable").data('confirmationchecker')
alert(x);
if (JSON.parse(x) == false) {
    alert("hi")
} 

How can I convert a string to boolean in JavaScript?

Community
  • 1
  • 1
RSquared
  • 1,168
  • 9
  • 19
0

Seems like the value of x is "false" string type, please try :

if ( x == "false") {
    alert("hi")
}

or cast your variable x to a bool type.

Aldo
  • 204
  • 1
  • 7