Reputation: 115
I'm having an issue with some numbers. Currently, I have an input box that displays the result of an equation. If the numbers are between "-25" and "-55", they display green. If the numbers are from "-55" to "-65", they are orange. Anything else outside of those ranges are red. The problem that I am having is that numbers "-3", "-4" and "-5" are all outside of that range, but they display as green. "-6" displays as orange. Those numbers should be red. Am I missing something from my code that would fix that?
Thank you!
var tb = (num1 * num2) + num3 + num4 + num5 + num6 + num7 + num8 + num9 + num10 + num11 + num13 + num12 + num14;
if (tb > 0) {
document.calcForm.resist.value = "+" + Math.floor(tb* 100)/100 + " dBm";
}
else
{
document.calcForm.resist.value = Math.floor(tb* 100)/100 + " dBm";
}
document.calcForm.resist.style.color = "green";
if (document.calcForm.resist.value < "-26" || document.calcForm.resist.value > "-65") {
document.calcForm.resist.style.color = "red";
}
else { if (document.calcForm.resist.value > "-55") {
document.calcForm.resist.style.color = "orange";
}}
num1 - num14 are different fields for the equation.
Upvotes: 0
Views: 72
Reputation: 1692
You were comparing strings to strings, which compares alphabetically, not by value. So, you need to convert document.calcForm.resist.value
to a number – parseInt(resist.value)
(see code):
var tb = (num1 * num2) + num3 + num4 + num5 + num6 + num7 + num8 + num9 + num10 + num11 + num13 + num12 + num14;
var resist = document.calcForm.resist;
if (tb > 0) {
resist.value = "+" + Math.floor(tb* 100)/100 + " dBm";
}
else
{
resist.value = Math.floor(tb* 100)/100 + " dBm";
}
resist.style.color = "green";
if (parseInt(resist.value) < -26 ||
parseInt(resist.value) > -65) {
resist.style.color = "red";
}
else if (parseInt(resist.value) > -55) {
resist.style.color = "orange";
}
Upvotes: 3
Reputation: 185
That happens due to the fact that document.calcForm.resist.value is being treated as string/text because you add "+" and + " dBm" to it
document.calcForm.resist.value = "+" + Math.floor(tb* 100)/100 + " dBm";
That's why "-3" > "-26", and "-3" < "-65".
Likewise for the rest.
Think of string comparison as: "-1" > "-10" > "-11"
whereas numerical: -1 < -10 < -11
In addition, you should remove the quotes from the numbers at:
if (document.calcForm.resist.value < "-26" || document.calcForm.resist.value > "-65")
to avoid invoking a string a comparison instead.
Upvotes: 0
Reputation: 463
You are trying to compare values with string type variables. You should not be using quotes for numeric data type.While using numeric comparisons you should use parseInt:
if (parseInt(document.calcForm.resist.value) < -26 || parseInt(document.calcForm.resist.value) > -65) {
document.calcForm.resist.style.color = "red";
}
Upvotes: 1