Reputation:
I am trying to create this JavaScript calculation with radio buttons. So If the user Checks the "delivered to home address" then the value of £5.99 will be added into the total box, but if the user selects the other radio button, then no price will get shown. I am pretty new to JavaScript so I may have a few errors, but i'd be grateful if you could help me out
<section id="collection">
<h2>Collection method</h2>
<p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
<p>
Home address - £5.99 <input type="radio" name="deliveryType" value="home" data-price="5.99" checked> |
Collect from ticket office - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0">
</p>
</section>
Total <input type="text" name="total" size="10" readonly>
let totalPrice = 0;
var RadioBtn = document.getElementById ('input[name=deliveryType]');
radioBtn.addEventListener("click", function() {
if(radioBtn.clicked) {
totalPrice += parseFloat(radioBtn.dataset.price)
total.value = " + totalPrice;
}
}
Upvotes: 0
Views: 66
Reputation: 413
Here are my observations from the code provided:
Example:
let totalPrice = 0;
let radioBtns = document.getElementsByName('deliveryType');
let totalEl = document.getElementsByName ('total')[0];
radioBtns.forEach(function(element, index){
element.addEventListener("click", function(event){
totalPrice += parseFloat(event.target.dataset.price); //remove += if the price should be the same everytime, replace with = or it will add the number to the total when clicked
totalEl.value = totalPrice + " totalPrice";
});
});
https://jsfiddle.net/dn4x7oy9/8/
Upvotes: 1