Reputation: 638
I recently started learning Javascript and I tought that I'll write a script that acts like a price calculator. The original price is 200. If a customer chooses first checkbox option it adds 50 to price, if second then add 150 to price, if both then add 150 and 50 to price. So far I have both of them working separately but they wont add amount to price if both checkboxes are checked.
How could I solve this problem? Should I use anything else than if...else?
Javascript
function myFunction() {
var price;
var originalprice = 200;
var firstprice = 0;
var secondprice = 0;
var checkBox = document.getElementById('myCheck');
var checkBox2 = document.getElementById('myCheck2');
if (checkBox.checked == true){
firstprice = 50;
}else if(checkBox2.checked == true){
secondprice = 150;
}
else {
price = originalprice;
}
var price = firstprice + secondprice + originalprice;
var el = document.getElementById('showprice');
el.textContent=price;
}
HTML
<h1>Check one or both of the checkboxes</h1>
Yes: <input type="checkbox" id="myCheck" onclick="myFunction()">
No: <input type="checkbox">
Yes: <input type="checkbox" id="myCheck2" onclick="myFunction()">
No: <input type="checkbox">
<div id="showprice">
</div>
Upvotes: 0
Views: 842
Reputation: 1296
you are trying to add value to the price , but this script will only work for one checkbox since you are using if else , simple remove the else here and put the default price at top no need to put it in else .
function myFunction() {
var originalprice = 200;
var firstprice = 0;
var secondprice = 0;
var price = originalprice;
var checkBox = document.getElementById('myCheck');
var checkBox2 = document.getElementById('myCheck2');
if (checkBox.checked == true){
firstprice = 50;
}
if(checkBox2.checked == true){
secondprice = 150;
}
var price = firstprice + secondprice + originalprice;
var el = document.getElementById('showprice');
el.textContent=price;
}
Upvotes: 1
Reputation: 1
If a customer chooses first checkbox option it adds 50 to price, if second then add 150 to price, if both then add 150 and 50 to price.
Since you want both you should use two if conditions instead of else if
, and even you don't have to specify the last else
, if two checkboxes
unchecked first and second price will takes initial value which is zero. So try this:
var originalprice = 200;
var firstprice = 0;
var secondprice = 0;
if (checkBox.checked == true){
firstprice = 50;
}
if(checkBox2.checked == true){
secondprice = 150;
}
var price = firstprice + secondprice + originalprice;
Upvotes: 1