function showNumber(selectId, divNumber) {
//this takes value from select option and grabs div for displaying it
var select = document.getElementById(selectId);
var noItems = document.getElementById(divNumber);
//loop for creating 0-20 drop down
for (var i = 0; i <= 20; i++) {
var option = document.createElement('option');
option.innerHTML = i;
option.value = i;
select.appendChild(option);
}
//onchange shows in a div how many items were selected
select.onchange = function () {
var noZero = select.value;
if (noZero > 0) {
noItems.innerHTML = noZero;
} else noItems.innerHTML = " ";
};
}
//function takes parameters of the previous one and displays number of items of a particular product in a div
function showDivs(){
showNumber('item1', 'div1');
showNumber('item2', 'div2');
showNumber('item3', 'div3');
showNumber('item4', 'div4');
}
我的问题是我想添加所有产品的数量(item1,item2等)以计算它们的总数。我似乎没有随处可见,任何帮助都非常感激!...
答案 0 :(得分:0)
在使用showNumber()
函数初始化项目时构建一个选择框数组,然后在onchange
事件中运行总计函数,检查每个项目中的值选择框。
// totaling vars (add #1)
var totalDiv = document.getElementById("divTotal"),
items = [];
function showNumber(selectId, divNumber) {
var select = document.getElementById(selectId);
select.onchange = function () {
...
calcTotal(); // run the total calculation with this event (add #4)
...
};
// add item to array (for checking totals) (add #2)
items.push(select);
}
...
// calculate totals using the items array (add #3)
function calcTotal() {
var totalQty = 0,
itemLen = items.length;
// loop through the items, sum values
for (var i = 0; i < itemLen; i++) {
totalQty += parseInt(items[i].value);
}
// show total
totalDiv.innerHTML = totalQty;
}