Tassisto
Tassisto

Reputation: 10345

Why does the value of a boolean change after stepping out of a function?

After I click on a li-element where the class-attribute contains "disabled selected", disabled gets the value "true" but after stepping out the function the last if-statement is called.

    var disabled = false;
    $("li").click(function () {
        if ($(this).attr("class") == "disabled selected") {
            disabled = true;
        }
    });
    if (disabled) {
        alert("disabled is true");
    }
    if (!disabled) {
        alert("disabled is false");
    }

Upvotes: 0

Views: 125

Answers (5)

pete
pete

Reputation: 25081

The problem is two-fold.

First, as pointed out by several posters, you need to put those if tests inside the click handler. As it stands now, they execute outside the click handler's scope, which I suspect is not when you want them to execute.

Second, the if ($(this).attr("class") == "disabled selected") { will only get you a "truthy" value if the class string is 'disabled selected'. If the class string is 'selected disabled' (or 'otherClass disabled selected' or 'disabled selected draggable', etc.) then you will get a false value returned as a result of the comparison.

Try:

$("li").click(function () {
    var i = $(this); //Multiple variables used for better step-line debugging.
    var hasDisabled = i.hasClass('disabled');
    var hasSelected = i.hasClass('selected');
    var disabled = false;
    if (hasDisabled && hasSelected) {
        disabled = true;
    }
    if (disabled) {
        alert("disabled is true");
    }
    if (!disabled) {
        alert("disabled is false");
    }
});

Upvotes: 0

Sapan Diwakar
Sapan Diwakar

Reputation: 10946

You should move both the if statements inside the click handler.

var disabled = false;
$("li").click(function () {
    if ($(this).attr("class") == "disabled selected") {
        disabled = true;
    }
    if (disabled) {
        alert("disabled is true");
    }
    else {
        alert("disabled is false");
    }
});

Upvotes: 4

osahyoun
osahyoun

Reputation: 5231

The callback is not invoked until the 'li' is clicked. However, the proceeding two 'if' statements are executed immediately. You'll want to place them within the callback.

var disabled = false;
$("li").click(function () {
    if ($(this).attr("class") == "disabled selected") {
        disabled = true;
    }
    if (disabled) {
     alert("disabled is true");
    }
    if (!disabled) {
     alert("disabled is false");
    }
});

Upvotes: 1

Supr
Supr

Reputation: 19032

The last two if tests are run before the click event handler, so the value of disabled hasn't been changed yet then.

Upvotes: 1

Emil
Emil

Reputation: 8527

The function is executed when the li element is clicked. When the script is initially evaluated, the click event has not been fired.

Upvotes: 0

Related Questions