pedram pedram - 7 months ago 26
Javascript Question

else if conditon not working

I'm stuck in a simple

else if
condition and believe it's first time I got issue with this. maybe I did something wrong, I dunno.



$('#lblShowCounter').each(function () {
if ($(this).text() >= '250') {
alert('red');
} else if ($(this).text() >= '300') {
alert('blink');
} else {
alert('nothing');
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="lblShowCounter">800</span>





the problem is this code only execute first
if
not
else if
looks like it wont check element text twice, right? but when I use this it works fine:



$('#lblShowCounter').each(function () {
if ($(this).text() >= '250') {
alert('red');
}
});

$('#lblShowCounter').each(function () {
if ($(this).text() >= '300') {
alert('blink');
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="lblShowCounter">800</span>





Thanks in advance

UPDATE: note that I want two alert, because 800 is greater than 300 and also greater than 250.

Answer

Since the question has since been updated to indicate you want 2 alerts.

With an if/elseif block, the block will complete once it hits the first match. So in your code, once it matches 250 the if statement completes and the elseif is never evaluated.

To get multiple conditions to execute independently, they should be multiple if statements:

$('#lblShowCounter').each(function () {
    var text = $(this).text(),
        matched;

    if (text >= '300') {
        alert('blink');
        matched = true;
    }
    if (text >= '250') {
        alert('red');
        matched = true;
    }

    if (!matched) {
        alert('nothing');
    }
});