简体   繁体   中英

Javascript if first and second checkbox checked add values to variable

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>

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;

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM