15

If the number is between two numbers plus + minus 10 addclass

http://jsfiddle.net/kM8xE/2/

If i have divs

<div class="value">15</div>
<div class="value2">20</div>​

and jQuery

var actual = $(".value").html();
var comparison = $(".value2").html();

how can I add a class .isbetweenin .value2if the html value is between +/- 10 html for .valuei.e. for this, for example. value from 5 to 25.

I am not too good, but I tried and it does not work.

if(parseInt(actual)-10 <= parseInt(comparison) <= parseInt(actual)+10){
$(".value2").addClass("isbetween");
}
+3
source share
3 answers
 if (Math.abs(actual - comparison) <= 10) {
    //they're within 10
 }
+10
source

The reason this doesn't work is because you cannot cling comparisons like this:

5 < x < 10

In Javascript (and other languages ​​with c-like syntax), you must make two separate comparisons and use logical and operator ( &&) to relate the comparisons:

var actualValue = parseInt(actual);
var comparisonValue = parseInt(comparison);

if(actualValue - 10 <= comparisonValue && comparisonValue <= actualValue + 10) {
    $(".value2").addClass("isbetween");
}

, . . .

, . , .

var delta = Math.abs(parseInt(actual) - parseInt(comparison));

if(delta <= 10) {
    $(".value2").addClass("isbetween");
}
+3

You need to get two values, convert them to numbers, compare the absolute value of their difference, and then add a class if it meets your condition:

var v1 = +$(".value").text();
var v2 = +$(".value2").text();
if (Math.abs(v1 - v2) <= 10) {
    $(".value2").addClass("isbetween");
}
0
source

All Articles