I’m trying to build an Ecommerce website. When you click/check a varietion it adds 20 on the total price 100. But when you uncheck the varietion it doesn’t minus on the total price. Please help me I’ve been trying this for months and it just won’t work.
Here’s my code:
<div id="total">500</div>
<input onclick="addTwenty()" id="checkbox1" type="checkbox">R20</input>
<script>
let total = document.getElementById("total");
let twenty = document.getElementById("checkbox1");
function addTwenty(){
total = 500;
twenty = 20;
if (twenty.checked = true){
document.getElementById("total").innerHTML = total + twenty;
} else{
document.getElementById("total").innerHTML = total - twenty;
}
}
</script>
I used If statements. When true, it adds value of 20 on 500, which is 520. But when unchecked it doesn’t minus 20. I want it to minus the same value it added when it’s now unchecked.
5
Answers
you should assign values to innerHTML not variables here.
=
is the assignment operator, not the equality check operator. You should use===
instead of=
, or better yet, since this is a Boolean, just omit it altogether:Change twenty variable name inside addTwenty function to amount, then it will work. And change your equal comparison from = to === .
You need to use the
==
or===
operator for the conditional comparison. You also are reassigningtwenty
within your function.But you can also just have
twenty.checked
since it will either be true or false itself.Solution:
Cause and explanation are given below.
when checked add 20, when unchecked it returns back to 500
Cause
on
line 8
you set twenty as the checkbox ->let twenty = document.getElementById("checkbox1");
But on
line 12
, you settwenty = 20;
so now the variable twenty does not contain the element, instead, it now has integer 20.Again, on
line 13
, in condition, you used(twenty.checked = true)
… But to make it clear to you,=
is used to assign value and==
is used to check/compare value, so you need to use==
here as(twenty.checked == true)
Solution Explanation
so, we take the checkbox as
twenty_check_box
instead oftwenty
and set it to constant. secondly, we check as(twenty_check_box.checked == true)
. and also update the total variable astotal += twenty
meaningtotal = total + twenty
and show it, so now total is 520then if unchecked, it subtracts 20 from
total
so nowtotal
is 500 again.Hope it solves the issue…