kyrillos ezzat
kyrillos ezzat

Reputation: 55

Add Radio button value to summation variable (javascript )

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

Upvotes: 1

Views: 49

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28404

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>

Upvotes: 1

Related Questions