Problem: Default checked radio button value shows on app, but if I change the tip value, then unselect and reselect a checkbox, it goes back to the original checked radio button value instead of changing to the new tip value.
Basicaly, my default radio checked button value is set to $5. If I select a checkbox option, then I change the tip value to $2 then unselect a checkbox, then reselect a checkbox, it will show the tip value as $5 instead of the new option $2
Here's my codepen. I added instructions on the codepen so you can see my problem
https://codepen.io/jaysomo10/pen/dydaKwZ
Here's my JS
window.menuItems = 0;
window.tips = 0;
const foodTotal = document.getElementById("price");
const tipTotal = document.getElementById("tip");
const orderTotal = document.getElementById("total");
let tipVal = document.querySelector(".tips:checked").value;
tipTotal.textContent = "$" + (tipVal / 100).toFixed(2);
document.addEventListener("click", ({ target }) => {
if (target.className === "food" && target.checked && tipVal) {
window.menuItems += parseInt(target.value);
window.tips = tipVal;
} else if (target.className === "food" && !target.checked) {
window.menuItems -= parseInt(target.value);
} else if (target.className === "tips" && target.checked) {
window.tips = parseInt(target.value);
} else {
return;
}
foodTotal.textContent = `$${(window.menuItems / 100).toFixed(2)}`;
tipTotal.textContent = `$${(window.tips / 100).toFixed(2)}`;
orderTotal.textContent = `$${(
(Number(window.menuItems) + Number(window.tips)) /
100
).toFixed(2)}`;
});
I can't seem to convert the logic to make the tip value to change after I unselect & re select a checkbox option.
tipVal is defined outside the click event. So it has always the value at the sart. You have to changhe it also inside the event
window.menuItems = 0;
window.tips = 0;
const foodTotal = document.getElementById("price");
const tipTotal = document.getElementById("tip");
const orderTotal = document.getElementById("total");
let tipVal = document.querySelector(".tips:checked").value;
tipTotal.textContent = "$" + (tipVal / 100).toFixed(2);
document.addEventListener("click", ({ target }) => {
tipVal = document.querySelector(".tips:checked").value;
if (target.className === "food" && target.checked && tipVal) {
window.menuItems += parseInt(target.value);
window.tips = tipVal;
} else if (target.className === "food" && !target.checked) {
window.menuItems -= parseInt(target.value);
} else if (target.className === "tips" && target.checked) {
window.tips = parseInt(target.value);
} else {
return;
}
foodTotal.textContent = `$${(window.menuItems / 100).toFixed(2)}`;
tipTotal.textContent = `$${(window.tips / 100).toFixed(2)}`;
orderTotal.textContent = `$${(
(Number(window.menuItems) + Number(window.tips)) /
100
).toFixed(2)}`;
});
remove this from your first if statement
if (target.className === "food" && target.checked && tipVal) {
window.menuItems += parseInt(target.value);
//window.tips = tipVal; // remove this
}