Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery if / else statement not consistent

I have the following code to check a decimal number from a dynamically updated div.

$('.numberfield').bind("DOMSubtreeModified", function()
{
    var $numbercheck = $(this).text().substring(1);

    if($numbercheck < 5.00) {
        console.log('lower than 5.00 ' + $numbercheck);  
    } 
    else {
        console.log('higher than 5.00 ' + $numbercheck);
    }
});

But when i reach a number higher than 5.00 it also triggers the lower if

Also, it seems to be triggering the IF condition no matter what.

> lower than 5.00 
> lower than 5.00 0.12

(2 lines triggered on each bind change)

> lower than 5.00 
> lower than 5.00 1.28

> lower than 5.00 
> higher than 5.00 12.89

> lower than 5.00 
> higher than 5.00 129.00

> lower than 5.00 
> higher than 5.00 129.00

So I guess the main problem is, why is the 'lower' always being triggered?

I am using Jquery 1.4.4

EDIT: I am thinking this may have something to do with the DOM being updated in 2 location simultaneously, thus triggering.

like image 485
petergus Avatar asked Feb 28 '26 05:02

petergus


1 Answers

You can use Unary plus (+) operator to convert +$numbercheck into a number.

And also you can refactor your code:

$('.numberfield').bind('DOMSubtreeModified', function () {
  var $numbercheck = $(this).text().substring(1),
      message = +$numbercheck < 5.00 ? 'lower than 5.00 ' : 'higher than 5.00 ';

  console.log(message + $numbercheck);
});
like image 158
Yosvel Quintero Arguelles Avatar answered Mar 01 '26 19:03

Yosvel Quintero Arguelles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!