价格计算器在javascript与价格上涨

时间:2015-02-27 02:29:22

标签: javascript

我希望为编辑论文制作价格计算器。我完成了第一部分(每天的单词jsfiddle)。

<label>Need in how many Days</label>
<input type="number" id="days" />
<br />
<label>Total Word Count</label>
<input type="number" id="words" />
<br />
<label>Price</label>
<input type="text" id="output" readonly />

我希望用户输入总字数和他们需要文档的天数,以显示每个项目的价格。我不知道如何将价格表添加到javascript并让它显示结果。该表是:

250字或更少=每字0.015美元,251-499 =每字0.020美元,500-1499 =每字0.025美元,1500-2499 =每字0.030美元,每天超过2500字=与我联系

感谢您的帮助。希望这是有道理的。

1 个答案:

答案 0 :(得分:0)

为了便于理解,我尝试在纯Javascript中尽可能明确地执行此操作。 这是HTML:

<label>Need in how many Days</label>
<input type="number" onkeyup="getValues()" id="days" />
<br />
<label>Total Word Count</label>
<input type="number" onkeyup="getValues()" id="words" />
<br />
<label>Price</label>
<input type="text" id="output" readonly />
<br />

这是JavaScript:

var days, words, output;

//think of the prices as t-shirt sizes
var extraSmall = 0.015,
    small = 0.020,
    medium = 0.025,
    large = 0.030,
    extraLarge = 0.035,
    extraExtraLarge = 'contact me';

// now you go into the dom and get the values you need
window.getValues = function () {
    var pricePerWord = 0;
    days = document.getElementById('days').value;
    words = document.getElementById('words').value;

    if(words > 2500) {
        if(days == 1) {
            pricePerWord = extraExtraLarge;
        } else {
            pricePerWord = extraLarge;
        }
        } else if (words >= 1500) {
            pricePerWord = large;
        } else if (words >= 500) {
            pricePerWord = medium;
        } else if (words >= 251) {
            pricePerWord = small;
        } else {
            pricePerWord = extraSmall;
        }

    // call the calculate function to do the math and update the dom
    calculate(pricePerWord, words, days);
}

window.calculate = function (pricePerWord, words, days) {
    var total;
    if(pricePerWord === extraExtraLarge) {
        total = extraExtraLarge;
    } else {
        total = Math.ceil(pricePerWord * words / days);
    }
    output = document.getElementById('output');
    if(days !== '' && days != 0) {
        output.value = total;
    } else {
        output.value = 0; // prevent 'Nan' and 'Infinity' from showing up
    }
}

注意:代码使用'window.calculate',因为它使它在jsfidle中工作,但它应该在没有'window'的情况下工作。参与你的代码。

希望它有所帮助!

相关问题