I am having a difficulty in displaying the value of totalPrice into my console. I am just getting 0 in my console but I want to get the actual value of each radio button. Can anyone help me please?
html
<lable>Radio1</lable>
<input type="radio" id="radio1" name="pay" class="myPay" value="2"/>
<label>Radio2</label>
<input type="radio" id="radio2" name="pay" class="myPay" value="3" />
js code
var totalPrice = 0;
var radio = document.querySelectorAll(".myPay");
radio.forEach(check => {
check.addEventListener('click', function(e) {
totalPrice = e.target.value;
});
});
console.log(totalPrice);
consolingyour variable on page load, it won't get the total value. Even if you throw the console at the end of your code, it is still ran BEFORE the code in your event listener.totalPricebefore the user has a chance to interact with the radio buttons and therefore change its value. Just move that last line inside the event handler.