jQuery中基于输入数字的不同公式

时间:2014-06-15 01:50:47

标签: javascript jquery formula conditional-statements conditional-operator

我想根据输入的数字使用不同的公式。例如,如果数字大于25,000,000,则将执行一次计算。如果数字小于25,000,000但大于10,000,000,则将执行另一次计算,等等。

有关如何进行以下工作的任何建议:

HTML:

<input type="text" id="calculation" name="submitted[calculation]" maxlength="20" class="form-text required">

jQuery的:

$("#calculation").change(function () {
    if (parseFloat(this.value) >= 25000000) {
        alert("court determines rate");
        if (parseFloat(this.value)( < 25000000 && >= 10000000)) {
            alert(113000 + (((this.value) - 10000000) * 0.005));
            if (parseFloat(this.value)( >= 1000000 && < 10000000)) alert(23000 + (((this.value) - 1000000) * 0.01));
            if (parseFloat(this.value)( >= 200000 && < 1000000)) alert(7000 + (((this.value) - 200000) * 0.02));
            if (parseFloat(this.value)( >= 100000 && < 200000)) alert(4000 + (((this.value) - 100000) * 0.03));

            else {
                alert((this.value) * .04)
            }
        })
});

更新:我已经更新了代码(再次),但仍然没有运气。有任何建设性的建议吗?

$("#calculation").change(function () {
var entry = parseFloat(this.value);

if (entry >= 25000000) {

    alert("court determines rate");
    }
else if (entry >= 10000000)) {
        alert(113000 + (((this.value) - 10000000) * 0.005));
        }
else (entry >= 1000000) {
    alert(23000 + (((this.value) - 1000000) * 0.01));
    }
else (entry >= 200000) {
    alert(7000 + (((this.value) - 200000) * 0.02));
    }
else (entry >= 100000) {
    alert(4000 + (((this.value) - 100000) * 0.03));
    }

        else {
            alert((this.value) * .04);
        }
    })
})

2 个答案:

答案 0 :(得分:1)

您在上面使用的语法非常难以阅读且无效。你应该只使用一次parseFloat而不是在任何地方使用它。以下是您应该做的一个非常简单的示例:

$("#calculation").change(function () {
    var parsedFloat = parseFloat(this.value);

    if (parsedFloat > 25000000){
        console.log('use formula 1. Number is greater than 25000000');
    }
    else if (parsedFloat > 10000000){
        console.log('use formula2. Number is greater than 10000000 and less than or equal to 25000000');
    }
    else {
        console.log('use formula3. Number is less than or equal to 10000000');
    }
});

答案 1 :(得分:0)

经过一些试验和错误之后,我发现了问题。第一个elseif中有一个额外的结束括号。

以下是更正后的代码:

$(document).ready(function () {

$("#calculation").change(function () {

var entry = parseFloat(this.value);


  if (entry >= 25000000) {
        alert("court determines rate");
    } else if (entry >= 10000000) {
    alert(113000 + (((this.value) - 10000000) * 0.005));
} else if(entry >= 1000000) {
    alert(23000 + (((this.value) - 1000000) * 0.01));
} else if (entry >= 200000) {
    alert(7000 + (((this.value) - 200000) * 0.02));
} else if (entry >= 100000) {
    alert(4000 + (((this.value) - 100000) * 0.03));
} else {
    alert((this.value) * .04);
}

});
});