Newbie Newbie - 11 days ago 8
C# Question

if statement in jquery Isn't working

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")
}

Answer

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")
}