if I have a variable like sum = 20 and I have a numbers of radio buttons with value(number) for each one of them how can I add the value of checked radio button only to sum variable and when check another radio button value will add to sum variable and remove other checked radio value before
1 Answer
You need to add event listeners to the inputs and change the sum accordingly:
let radios = document.getElementsByClassName("numberRadio");
let number = 20;
sum.innerHTML = number;
for(let i = 0; i < radios.length; i++)
radios[i].addEventListener("click", addNumbers);
function addNumbers(event){
let total = number;
for(let i = 0; i < radios.length; i++)
if(radios[i].checked)
total += parseInt(radios[i].value);
sum.innerHTML = total;
}
<input type="radio" class="numberRadio" id="one" name="number" value="1">
<label for="one">1</label><br>
<input type="radio" class="numberRadio" id="two" name="number" value="2">
<label for="two">2</label><br>
<input type="radio" class="numberRadio" id="three" name="number" value="3">
<label for="three">3</label>
<br><br>
<input type="radio" class="numberRadio" id="four" name="number1" value="4">
<label for="four">4</label><br>
<input type="radio" class="numberRadio" id="five" name="number1" value="5">
<label for="five">5</label><br>
<input type="radio" class="numberRadio" id="six" name="number1" value="6">
<label for="six">6</label>
<p id="sum"></p>
2 Comments
kyrillos ezzat
Thanks, dude, I appreciate it, but this work for just one group of radio buttons I have multi groups and I wanna make a function for all
Majed Badawi
@kyrillosezzat I updated the answer. Please mark the answer as the solution to close the question.