javascript “less than” if statement failing

夙愿已清 提交于 2020-03-01 18:32:51

问题


Here is my function:

function reCalculate(i) {
    document.getElementById("Q" + i).value = document.getElementById("C" + i).value - document.getElementById("QA" + i).value;

    if (document.getElementById("Q" + i).value < 0) {
        document.getElementById("Q" + i).value = 0;
    }
    if (document.getElementById("Q" + i).value < document.getElementById("E" + i).value && document.getElementById("Q" + i).value != 0) {
        alert(document.getElementById("Q" + i).value + " is less than " + document.getElementById("E" + i).value + "?");
        document.getElementById("Q" + i).value = document.getElementById("E" + i).value;
    }
    document.getElementById("Q" + i).value = Math.ceil(document.getElementById("Q" + i).value);
}

It checks Q, if it's less than 0, it makes it 0. Then, if it's not 0, but it's less than E, it makes it E. For some reason this function works UNLESS Q is a double digit number.

For example, if Q is 7 and E is 2, then it will leave Q at 7. However, if Q is 10 and E is 2, for some reason it thinks that 10<2, and it changes Q to 2!

Am I missing something here??


回答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)



回答2:


Thats because it is considering your Q as a string while comparing.

Try the following instead:

function reCalculate(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);
}



回答3:


May be you should do a

parseFloat(document.getElementById("Q"+i).value)

to make sure you are comparing numbers




回答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) {

}


来源:https://stackoverflow.com/questions/14056878/javascript-less-than-if-statement-failing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!