Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
}
like image 788
Newbie Avatar asked Mar 11 '23 13:03

Newbie


2 Answers

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")
}
like image 112
John Wu Avatar answered Mar 19 '23 20:03

John Wu


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?

like image 28
RSquared Avatar answered Mar 19 '23 21:03

RSquared