Javascript "less Than" If Statement Failing
Here is my function: function reCalculate(i) { document.getElementById('Q' + i).value = document.getElementById('C' + i).value - document.getElementById('QA' + i).value; i
Solution 1:
When you pull the .value
of an element it returns a string. '10'<'2'
will return true.
You can simply do a parseInt/parseFloat on the value, ala
var q = parseInt(document.getElementById("Q"+i).value,10)
Solution 2:
Thats because it is considering your Q
as a string while comparing.
Try the following instead:
functionreCalculate(i){
var Z = document.getElementById, P = parseInt;
var qElem = Z("Q"+i);
var q = P(qElem.value, 10);
var c = P(Z("C"+i).value, 10);
var qa = P(Z("QA"+i).value, 10);
var e = P(Z("E"+i).value, 10);
q = c - qa;
if (q < 0) qElem.value = 0;
if (q < e && q != 0){
alert(q+" is less than "+e+"?");
qElem.value = e;
}
qElem.value = Math.ceil(q);
}
Solution 3:
May be you should do a
parseFloat(document.getElementById("Q"+i).value)
to make sure you are comparing numbers
Solution 4:
You are comparing strings not numbers. Use the unary +
to convert to a number:
if (+document.getElementById("Q" + i).value < +document.getElementById("E" + i).value ...)
You should use variables by the way:
var input_one = document.getElementById("Q" + i).value,
input_two = document.getElementById("E" + i).value;
if (+input_one < +input_two) {
}
Post a Comment for "Javascript "less Than" If Statement Failing"