从选择菜单选项到另一个表格单元
问题描述:
我有一个简单的HTML表格,允许用户从选择菜单中进行选择,然后在下一列中输入数量。从选择菜单选项到另一个表格单元
我需要能够自动计算每个选择的QTY列的总计 - 行数不固定,但始终至少为1行。我创建了我的表的简化版本在这里:
这里,用户只能从3种不同的水果(苹果,香蕉,芒果)中进行选择,然后输入数量每个。一旦用户进行水果选择和/或输入数量,我想自动计算每种水果的总量。在我的例子中,总计将是:
共苹果:20个 总香蕉:30个 总芒果:5
我很高兴能使用jQuery如果这能帮助 - 我一直在寻找,并不能查找类似解决方案的示例,该解决方案计算选择菜单中每行的选择数量,然后计算该行中另一列的总数。
欣赏是否有人能够启发我如何实现这一点,或者如果您可以指出任何类似的例子。我在这个阶段是一个Javascript新手。
答
$('#fruits')
.on('change', 'select', calc)
.on('keyup', 'input', calc);
$(document).ready(calc);
function calc(){
var total = {};
$('#fruits tr:has(.fruit)').each(function(){
var $t = $(this),
// val : Apple | Banana | Mango
val = $t.find('.fruit select').val(),
qty = $t.find('input').val();
// the qty
qty = Number(qty);
qty = isNaN(qty)?0:qty;
if(!total.hasOwnProperty(val)) total[val] = 0;
total[val] += qty;
});
// you would be updating the actual html here.
for(val in total){
if(total.hasOwnProperty(val)){
// NOTE that I change your 'sumApples' to 'sumApple' which follows convention of 'sum' + { the name of the fruit }
$('#sum' + val).html(total[val]);
}
}
}
答
我已经添加了一个苹果总和的例子。看到这个example。
$('.qty').change(function(){
sumApples();
});
$('.fruit').change(function(){
sumApples();
});
function sumApples(){
var totalApples = 0;
$('#fruits').find('select').each(function(){
if ($(this).val() == 'Apple'){
var q = $(this).parent('td.fruit').next('td').find('.qty').val();
totalApples += parseInt(q);
}
});
$('#sumApples').html(totalApples);
}
答
$().ready(function(){
var fruit=[];
$('table select').each(function(){
if(!fruit[$(this).find('option:selected').text()])
fruit[$(this).find('option:selected').text()]=0;
fruit[$(this).find('option:selected').text()]+=parseInt($(this).parent().next().find('.qty').val());
});
$('#sumApples').text(fruit['Apple']);
$('#sumBananas').text(fruit['Banana']);
$('#sumMangoes').text(fruit['Mango']);
});
这是例子,检查此链接也 http://jsfiddle.net/T5xtL/7/
答
我就告诉你了香蕉的样本,我相信你会知道如何推广这为你的其他产品。
// Filter only returns the values where the inner function returns true
var bananas = $('.fruits').filter(function() {
// this selector returns the selected options
if ($(':selected', this).val() === 'Banana') {
return true;
}
}
// Now, for each banana, get its quantity, and add to the total
bananas.each(function() {
// Get the quantity
var qty = $(this).next().find('input').val();
// Add it to the bananas quantity
// parseInt transforms a text to an integer
var qty = qty + parseInt($('#sumBananas').text(), 10);
// And set the quantity in the "sumBananas" span
$('#sumBananas').text(qty);
});
感谢亮亮 - 在我的快速测试效果很好。非常感激。 – user982124