vendredi 7 mai 2021

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>

Aucun commentaire:

Enregistrer un commentaire