Warm tip: This article is reproduced from stackoverflow.com, please click
button html javascript onclick onclicklistener

Javascript

发布于 2020-03-28 23:16:48

So I'm trying to count the number of items that the user adds to their cart, as well as print the total cost of all items selected. Counting the number of items works properly, but I'm struggling to figure out how to access the specific cost associated with each item the user chooses to select and take the sum of all of those items together, representing the variable totalCost.

For example, if the user clicks Add next to the iMac as well as Add next to the Windows PC, the total cost should be 2000 + 1300 = 3300. In the calculate() function, I attempted to iterate through all the items under the electronics department and check if the user clicked a button next to a certain item but it messed up my program which is why I commented the function out. Similar to the count variable, I'm trying to successfully get the total cost to update every time the user chooses to add something to their cart. Any guidance would be appreciated.

let count = 0;
let totalCost = 0;

function init() {
  count = 0;
  let button = document.getElementById("but");
  button.onclick = buttonClicked;
}

function buttonClicked() {
  count++;
  let div = document.getElementById("coutner");
  div.innerHTML = "You have " + count + " items and a total cost of $" + totalCost;
}

function showOptions(el) {
  let userPicked = el.value;
  var div = document.getElementById("div");
  if (userPicked != 'none') {
    var newContent = (electronics.store);
    newContent += '<div>';
    Object.keys(electronics.inventory).forEach(key => {
      newContent += key;
      newContent += '<div>';
      var items = Object.values(electronics.inventory[key]);
      items.forEach(item => {
        newContent += '<div>';
        newContent += `&nbsp; <span class="brand"> ${item.brand} </span>  <span class="price">$${item.cost}</span>`;
        newContent += `<input type=button value="Add" onclick="add(this)"/>`
        newContent += '</div>';
      });
      newContent += '</div>';
    });
    newContent += '</div>';
    div.innerHTML = newContent;
  }
}

function add(add) {
  console.clear();
  console.log(add.closest('div').textContent.trim());
  buttonClicked();
}


let electronics = {
  store: "Mike's Computers",
  inventory: {
    "Laptops": {
      0: {
        brand: "iMac",
        cost: 2000
      },
      1: {
        brand: "Dell",
        cost: 600
      }
    },
    "Computers": {
      2: {
        brand: "Windows PC",
        cost: 1300
      }
    }
  }
};
<div>
  <h1>Welcome</h1>
</div><br />
<div class="dropdown">
  <form>
    <select name="list" id="list" accesskey="target" onchange="showOptions(this); buttonClicked(this)">
      <option value="none">Select a restaurant</option>
      <option value="Electronics">Electronics</option>
    </select>
    <input type=button id="but" value="Select" onclick="showOptions(); buttonClicked()" />
    <div><mark id="coutner"></mark></div>
  </form>

</div>
<div id="div"></div>

I kept getting a formatting error when trying to show my comment so here it is separately (it was in the js file below init())

/*
function calculate(){
    if(userPicked == 'Electronics'){
        Object.keys(electronics.menu).forEach(key => {
             var items = Object.values(electronics.menu[key]);
               items.forEach(item => {
                  if(buttonClicked(){
                      totalCost += item.cost;
                  }
             });
        }); 
    }
}
*/
Questioner
Grayish
Viewed
30
43.2k 2020-01-31 18:35

You can fix your code by passing the item cost in to the add() function.

Also I have renamed your function buttonClicked to what it actually does - updating the display.

Always try to keep your functions clean and only have them do one thing at a time. By moving the count++ from the update function into the place where it actually belongs - the add function - you separate functionality and also fix your off-by-one error in the display.

let count = 0;
let totalCost = 0;
let div = document.getElementById("coutner");

function init() {
  count = 0;
  let button = document.getElementById("but");
  button.onclick = updateDisplay;
}

function updateDisplay() {
  div.innerHTML = `You have ${count} items and a total cost of $${totalCost}`;
}

function showOptions(el) {
  let userPicked = el.value;
  var div = document.getElementById("div");
  if (userPicked != 'none') {
    var newContent = (electronics.store);
    newContent += '<div>';
    Object.keys(electronics.inventory).forEach(key => {
      newContent += key;
      newContent += '<div>';
      var items = Object.values(electronics.inventory[key]);
      items.forEach(item => {
        newContent += `
<div>&nbsp;
  <span class="brand"> ${item.brand}</span>
  <span class="price">$${item.cost}</span>
  <input type=button value="Add" onclick="add(this,${item.cost})"/>
</div>`;
      });
      newContent += '</div>';
    });
    newContent += '</div>';
    div.innerHTML = newContent;
  }
}

function add(element,cost) {
  console.clear();
  totalCost += parseInt(cost);
  count++;
  console.log(element.closest('div').textContent.trim());
  updateDisplay();
}


let electronics = {
  store: "Mike's Computers",
  inventory: {
    "Laptops": {
      0: {
        brand: "iMac",
        cost: 2000
      },
      1: {
        brand: "Dell",
        cost: 600
      }
    },
    "Computers": {
      2: {
        brand: "Windows PC",
        cost: 1300
      }
    }
  }
};
<div>
  <h1>Welcome</h1>
</div><br />
<div class="dropdown">
  <form>
    <select name="list" id="list" accesskey="target" onchange="showOptions(this); updateDisplay(this)">
      <option value="none">Select a restaurant</option>
      <option value="Electronics">Electronics</option>
    </select>
    <input type=button id="but" value="Select" onclick="showOptions(); updateDisplay()" />
    <div><mark id="coutner"></mark></div>
  </form>

</div>
<div id="div"></div>