7

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

If I have the 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 class .isbetween to .value2 if it's html value is between +/-10 of the html for .value ie. for this eg. a value between 5 and 25.

I am not too good but i have tried and it doesn't work.

if(parseInt(actual)-10 <= parseInt(comparison) <= parseInt(actual)+10){
$(".value2").addClass("isbetween");
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Yusaf Khaliq
  • 3,333
  • 11
  • 42
  • 82
  • The fiddle seems to work, insofar as the `value2` class is highlighted. I read your post a few times and I'm still not quite sure what isn't right (a good rule of thumb: if you have to say "it doesn't work" then rewrite the question. In response to such as statement, people will always say: "what _specifically_ should happen?). – halfer Apr 28 '12 at 22:20

3 Answers3

18
 if (Math.abs(actual - comparison) <= 10) {
    //they're within 10
 }
Marc
  • 11,403
  • 2
  • 35
  • 45
3

The reason this doesn't work is that you can't chain comparisons like this:

5 < x < 10

In Javascript (and other languages with c-like syntax), you have to make two separate comparisons, and use the boolean and operator (&&) to chain the comparisons together:

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

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

Also, don't repeat yourself. Do the conversion once, and store it in a local variable. This makes the code much more readable.

This can be made even more simple by using a concept called absolute value. Then you can just do your difference, and see if its absolute value is less than or equal to ten.

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

if(delta <= 10) {
    $(".value2").addClass("isbetween");
}
Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
0

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

var v1 = +$(".value").text();
var v2 = +$(".value2").text();
if (Math.abs(v1 - v2) <= 10) {
    $(".value2").addClass("isbetween");
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979