'change multiple prices with checkbox
I've been trying to create a pricing table where monthly price is given and a checkbox from where you can toggle between monthly and annually prices. I have 8 price cards with different prices. First I got the classes and ids of the checkbox and price labels and with js function I'm trying to change the prices. But when I check the first time the prices are multiplying but when unchecked, the prices do not return to original. And later I'm getting NaN values.
html
<label class="switch">
<input
type="checkbox"
id="price-checkbox"
onclick="changePrice('price-checkbox', 'price');"
/>
<span class="slider round"></span>
</label>
<div class="card text-center">
<div class="card-body">
<h5 class="card-title text-uppercase fw-bold mb-3">Basic</h5>
<h6 class="card-subtitle my-2">
<span class="price fs-4 fw-bold">540.00</span> per month
</h6>
<p class="card-text my-4">50,000 Minutes- SIP</p>
<p class="card-text mb-4">50,000 minutes monthly renewal</p>
<div class="btn-container">
<button class="btn" type="button">Purchase Now</button>
</div>
</div>
</div>
<div class="card text-center">
<div class="card-body">
<h5 class="card-title text-uppercase fw-bold mb-3">ADVANCED</h5>
<h6 class="card-subtitle my-2">
<span class="price fs-4 fw-bold">990.00</span> per month
</h6>
<p class="card-text my-4">50,000 Minutes- SIP</p>
<p class="card-text mb-4">50,000 minutes monthly renewal</p>
<div class="btn-container">
<button class="btn" type="button">Purchase Now</button>
</div>
</div>
</div>
<div class="card text-center">
<div class="card-body">
<h5 class="card-title text-uppercase fw-bold mb-3">Premium</h5>
<h6 class="card-subtitle my-2">
<span class="price fs-4 fw-bold">2025.00</span> per month
</h6>
<p class="card-text my-4">50,000 Minutes- SIP</p>
<p class="card-text mb-4">50,000 minutes monthly renewal</p>
<div class="btn-container">
<button class="btn" type="button">Purchase Now</button>
</div>
</div>
</div>
JS
function changePrice(id, label) {
const chkbox = document.getElementById(id);
const price = document.getElementsByClassName(label);
let prevPrice = [];
for (let i = 0; i < price.length; i++) {
console.log(parseFloat(price[i].innerHTML));
prevPrice.push(parseFloat(price[i].innerHTML));
}
if (chkbox.checked) {
for (let i = 0; i < price.length; i++) {
price[i].innerHTML = parseFloat(price[i].innerHTML) * 12;
}
} else {
for (let i = 0; i < price.length; i++) {
price[i].innerHTML = prevPrice[i];
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
