[英]retrieve quantity from dynamic js menu
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等),以便計算它們的總數。 我似乎對此一無所獲,非常感謝任何幫助!
使用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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.