I am newbie in Javascript. I am trying to achieve to add the price of certain color and size. With this, the prices of each variant are as follows:
White, Small = 41
Black, Small = 51
White, Medium = 45
Black, Medium = 55
I would like to display the sum of it in HTML.
var sizeprice = 0, colorprice = 0; // added by Mr Jojo
function ColorWhite() {
colorprice = 40
sumcolorandprice = colorprice sizeprice
document.getElementById("current-price").innerHTML = '$' sumcolorandprice
}
function ColorBlack() {
colorprice = 50
sumcolorandprice = colorprice sizeprice
document.getElementById("current-price").innerHTML = '$' sumcolorandprice
}
function SizeSmall() {
sizeprice = 1
sumcolorandprice = colorprice sizeprice
document.getElementById("current-price").innerHTML = '$' sumcolorandprice
}
function SizeMedium() {
sizeprice = 5
sumcolorandprice = colorprice sizeprice
document.getElementById("current-price").innerHTML = '$' sumcolorandprice
}
<span id="current-price"></span>
<button type="button" onclick="ColorWhite()">White</button>
<button type="button" onclick="ColorBlack()">Black</button>
<button type="button" onclick="SizeSmall()">Small</button>
<button type="button" onclick="SizeMedium()">Medium</button>
CodePudding user response:
Consider the following jQuery example.
$(function() {
var sumPrice = 0;
var prices = {
white: 40,
black: 50,
small: 1,
medium: 5
};
function showCurrency(p) {
return "$" p.toFixed(2);
}
function setColor(c) {
sumPrice = prices[c];
$("#current-price").html(showCurrency(sumPrice));
}
function setSize(s) {
sumPrice = prices[s];
$("#current-price").html(showCurrency(sumPrice));
}
$(".color").click(function() {
setColor($(this).val());
});
$(".size").click(function() {
setSize($(this).val());
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="current-price"></span>
<button type="button" value="white">White</button>
<button type="button" value="black">Black</button>
<button type="button" value="small">Small</button>
<button type="button" value="medium">Medium</button>
This may not be the best way to capture this type of user interaction. The User can click buttons multiple times and there is no way for you to determine if they hit it once or more than once, for any of the buttons.
You can see that when the user clicks a button it adds the price to the sumPrice
, if they click another button, the price is updated. We defined sumPrice
as a more global variable, meaning other functions can access it. We can do this with:
sumPrice = sumPrice prices['white'];
This same bit of code can use another operator for shorthand:
sumPrice = prices['white'];
Most of all this can also be done with JavaScript in much the same way.
var sumPrice = 0;
var prices = {
white: 40,
black: 50,
small: 1,
medium: 5
};
function showCurrency(p) {
return "$" p.toFixed(2);
}
function setColor(c) {
sumPrice = prices[c];
$("#current-price").html(showCurrency(sumPrice));
}
function setSize(s) {
sumPrice = prices[s];
$("#current-price").html(showCurrency(sumPrice));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="current-price"></span>
<button type="button" value="white" onclick="setColor(this.value);">White</button>
<button type="button" value="black" onclick="setColor(this.value);">Black</button>
<button type="button" value="small" onclick="setSize(this.value);">Small</button>
<button type="button" value="medium" onclick="setSize(this.value);">Medium</button>
Update
If you want the User to only select one Color and one Size, you might consider using Radio Buttons instead of Buttons. See More: https://www.w3schools.com/tags/att_input_type_radio.asp
Here is an example.
var sumPrice = 0;
var prices = {
white: 40,
black: 50,
small: 1,
medium: 5
};
function showCurrency(p) {
return "$" p.toFixed(2);
}
function calcTotal(event) {
var c = 0;
var s = 0;
if (document.querySelector('input[name="color"]:checked')) {
c = prices[document.querySelector('input[name="color"]:checked').value];
}
if (document.querySelector('input[name="size"]:checked')) {
s = prices[document.querySelector('input[name="size"]:checked').value];
}
document.querySelector('#current-price').innerHTML = showCurrency(c s);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
Select Color:
<input type="radio" value="white" name="color" onclick="calcTotal()"> <label>White</label>
<input type="radio" value="black" name="color" onclick="calcTotal()"> <label>Black</label>
</div>
<div >
Select Size:
<input type="radio" value="small" name="size" onclick="calcTotal()"> <label>Small</label>
<input type="radio" value="medium" name="size" onclick="calcTotal()"> <label>Medium</label>
</div>
Price: <span id="current-price">$0</span>
CodePudding user response:
I took a stab at coding this using some better practices. I introduced an IIFE, Closures and addEventListener to avoid using global variables, and used better naming practices. You want to avoid using an upper case letter as the first letter in a function name generally because people use that to denote that the function should be treated like a Class. The logic here is to only show the price once both a color and a size are chosen. If you want price to show as soon as the first button is clicked simply take the code that is inside the if
statement and put it outside the if
block and then delete the if
statement logic.
/* Immediately invoked function expression wrapping all the code
and passing in the global object, which in the case of the
browser is the window
*/
(function (global) {
'use strict'; // Best practice to always use strict mode
const doc = global.document;
/* Keep track of default price constants in a single object.
If prices changes in future it will be easy to modify
them from one spot
*/
const prices = {
white: 40,
black: 50,
small: 1,
medium: 5
}
// Use to get, set, calculate, and print prices
const currentPrice = (() => {
// These variables now protected in a closure and accessed
// with the currentPrice object's methods (returned below)
let sizePrice = 0,
colorPrice = 0,
totalPrice = 0;
return {
getSizePrice() {
return sizePrice;
},
getColorPrice() {
return colorPrice;
},
getTotalPrice() {
return totalPrice;
},
setSizePrice(price) {
sizePrice = price;
},
setColorPrice(price) {
colorPrice = price;
},
calcTotalPrice() {
totalPrice = sizePrice colorPrice;
},
printTotalPrice() {
doc.getElementById('totalPrice').textContent = `$${totalPrice}`;
}
}
})();
// Using single Event Listener for row of btns is best practice
doc.getElementById('btnRow').addEventListener('click', function (evt) {
// After listening for the click this determines which btn
// was clicked and adds the unique code for that btn
switch (evt.target.id) {
case 'btnColorWhite':
currentPrice.setColorPrice(prices.white);
break;
case 'btnColorBlack':
currentPrice.setColorPrice(prices.black);
break;
case 'btnSizeSm':
currentPrice.setSizePrice(prices.small);
break;
case 'btnSizeMd':
currentPrice.setSizePrice(prices.medium);
break;
}
// Only calculates and prints the price if both a color and
// size have been clicked already
if (currentPrice.getColorPrice() !== 0 && currentPrice.getSizePrice() !== 0) {
currentPrice.calcTotalPrice();
currentPrice.printTotalPrice();
}
evt.stopPropagation();
}, { passive: true });
})(window);
.buttons-wrapper {
display: inline-block;
}
<div id="btnRow">
<button type="button" id="btnColorWhite">White</button>
<button type="button" id="btnColorBlack">Black</button>
<button type="button" id="btnSizeSm">Small</button>
<button type="button" id="btnSizeMd">Medium</button>
</div>
<span id="totalPrice"></span>