I have an html file with a form for a person to fill out to take an order.
I have a global array to store objects. The objects contain the name, price, and quantity of the item added to the order.
<button type="button" onclick="addToOrder('app2-amount', 'House Salad', '6')">+</button>
This is where addToOrder() is called.
And the function:
var orderArray = [];
function addToOrder(id, nameIn, priceIn){
if (loggedIn == true){
var quantityIn = document.getElementById(id).value;
var totalForThisItem = priceIn*quantityIn;
var menuObject = {
name: nameIn,
price: totalForThisItem,
quantity: quantityIn
};
// Next we must perform a check to see if an object with the same name already exists in the order
// If it does exist, replace it with this new object.
if (orderArray.length == 0){
orderArray.push(menuObject);
}
else{
orderArray.forEach( function (item) {
if (item.name == menuObject.name){
item = menuObject;
}
else{
orderArray.push(menuObject);
}
});
}
console.log("dabs " + orderArray.toString());
}
// If user is not logged in:
else{
console.log("You are not logged in. Please log in to use this feature.");
}
console.log(menuObject);
}
When I print menuObject, I thought it would be out of scope, deleted. I am inserting it into a global variable, and I think it is screwing me over.
Some odd things happen when I starting putting different menu items into the array. In one case, it added 3, 6, 12, 24, etc. with each press. Kinda funny, but I'm pretty bummed.
What happens here?
When I print menuObject, I thought it would be out of scope, deletedIts because you are printing it within the function(at the end), its not yet out of scope. Other than that your question is not clear what exactly is your issue? put some example/scenarios with data to explain.item = menuObject;toitem.name = menuObject.name; item.price = menuObject.price; item.quantity = menuObject.quantityor rather insert directly into array{name: nameIn, price: totalForThisItem, quantity: quantityIn}is still adding multiple objects with a single click.