I am trying to learn JavaScript and want to learn from the bottom. I'm trying to code an cash register, and this is what I have got so far.
var egg = {
pName : "Egg",
price : 21.95,
discount : 20
}
var milk = {
pName : "Milk",
price : 4.95,
discount : 20
}
var juice = {
pName : "Juice",
price : 15.50,
discount : 0
}
var totalCost = 0;
var add = function(){
i = document.querySelector('.addIt').value;
productCost = "";
ProductName = "";
if (i === "egg") {
productCost = egg.price
ProductName = egg.pName
totalCost = totalCost + productCost;
addElement();
} else if (i === "milk") {
productCost = milk.price
ProductName = milk.pName
totalCost = totalCost + productCost;
addElement();
} else if (i === "juice") {
productCost = juice.price
ProductName = juice.pName
totalCost = totalCost + productCost;
addElement();
} else {
alert("Det kan du ikke købe!")
}
function addElement(){
var newDiv = document.createElement("div");
var newContent = document.createTextNode(ProductName + " " + productCost);
newDiv.appendChild(newContent);
var currentDiv = document.querySelector('.items');
currentDiv.appendChild(newDiv);
}
document.querySelector('.kvitt .totalPrice span').innerHTML = totalCost;
}
The HTML
<body>
Velkommen til min butik.
Her er hvad du kan købe: egg, milk, juice
<br>
Tast det her ---> <input class="addIt" type="text" ></input>
<button onclick="add();"> Tilføj vare</button>
<br />
<div class="kvitt">Kvitering
<div class="items">her</div>
<div class="totalPrice">Total pris : <span></span></div>
</div>
<script src="script.js"></script>
</body>
I know it's not perfect so don't judge, I'm trying to learn :)
What I want is to reduce the code a bit, but I can't seem to get it to work.
I want to call my object directly in my totalCost update.
Example: If i = egg
, then I should be able to write i.pName
, right? Or am I missing somthing? :)
UPDATE: I want to know how I can take the answer from the input, and make something like this = answer.price :)