我已经蒙混过关一段时间了.我有三个表单域:个人,情侣,总计。这是一个用于会议注册的费用计算器。
一个人(#个人)的费用是50美元。一对情侣(#情侣)的价格是75美元。如果注册总人数超过3人,则会有折扣。打折时每人40美元。因此,我们计算总人数,如果有3人或更多人,则对每个人应用40美元的新价格。在计算#个人和#夫妇字段之间的总人数之前,需要将#夫妇的值乘以2,因为每对夫妇有两个人。新的“折扣”#个人价格是40美元,新的#情侣价格是80美元。
我的问题很简单:“我哪里做错了?”任何洞察力都是非常值得欣赏的。
我当前的代码在#total字段中产生了错误的数字:
$('#individuals').change(compute);
$('#couples').change(compute);
function compute() {
var ind = $('#individuals').val(); // number of individuals
var coup = $('#couples').val()*2; // number of people in a couple (2)
var people = ind + coup; // add up the total people
if (people >= 3) {
var a = $('#individuals').val()*40; // discount price of an individual
var b = $('#couples').val()*80; // discount price of couple
}
else {
var a = $('#individuals').val()*50; // normal price of an individual
var b = $('#couples').val()*75; // normal price of couple
}
var total = a + b;
$('#total').val(total);
}发布于 2013-03-25 05:05:09
$('#element').val() parseInt(val, 10)来确保您的数字是数字而不是字符串。您的ind字段当前是一个字符串,当您将其“连接”到coup时会导致错误
例如:
function compute() {
var ind = parseInt($('#individuals').val(), 10); // number of individuals
var coup = parseInt($('#couples').val(), 10); // number of couples
var people = ind + 2 * coup; // add up the total people
var total;
if (people >= 3) {
total = 40 * people;
} else {
total = 50 * ind + 75 * coup;
}
$('#total').val(total);
}
$('#individuals,#couples').on('change', compute);https://stackoverflow.com/questions/15603962
复制相似问题