Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if number is between two numbers by plus/minus 10 addclass

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");
}
like image 443
Yusaf Khaliq Avatar asked Apr 28 '12 22:04

Yusaf Khaliq


People also ask

How do you check if a number is between two values?

Check if a cell value is between two values with formula Please apply the following formula to achieve it. 1. Select a blank cell which you need to display the result, enter formula =IF(AND(B2>A2,B2<A3),"Yes","No") into the Formula Bar and then press the Enter key.

How do I add two numbers in HTML?

You can then add numbers in the first two text boxes and store them in a variable such as "result," as follows: var result = Number(box1. value) + Number(box2. value); box3.

How do you write an addition program in JavaScript?

Example 2: Add Two Numbers Entered by the Userconst num1 = parseInt(prompt('Enter the first number ')); const num2 = parseInt(prompt('Enter the second number ')); Then, the sum of the numbers is computed. const sum = num1 + num2; Finally, the sum is displayed.


2 Answers

 if (Math.abs(actual - comparison) <= 10) {
    //they're within 10
 }
like image 90
Marc Avatar answered Oct 05 '22 23:10

Marc


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");
}
like image 21
Merlyn Morgan-Graham Avatar answered Oct 05 '22 23:10

Merlyn Morgan-Graham