1

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 1

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

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
@kyrillosezzat I updated the answer. Please mark the answer as the solution to close the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.