-1

I have radio inputs like this:

<input type="radio" name="battery" class="radio" value="0" id="63" />
<label for="63">SoH 63-65%</label>
<input type="radio" name="battery" class="radio" value="100" id="66" />
<label for="66">SoH 66-67%</label>
<input type="radio" name="battery" class="radio" value="200" id="68" />
<label for="68">SoH 68-69%</label>

and this:

    <input type="radio" name="year" class="radio" value="400" id="2015" />
    <label for="2015">2015 year</label>
    <input type="radio" name="year" class="radio" value="500" id="2016" />
    <label for="2016">2016 year</label>

Their walues sum up all values by clicking on this button

<button class="load-more-btn" id="sumUp>
  Sum up
</button>

And result should be outputted with this script:

document.getElementById("price").innerHTML = RESULTVALUE;

How can I do this?

  • 1
    Here are some starting points: `document.querySelectorAll("input[type=radio]:checked")` to get all the selected buttons. Loop over them. Use `.value` and `parseInt()` to get each value. Add the values to an accumulator variable. – Barmar Aug 14 '21 at 18:26
  • 2
    [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+sum+of+checked+radio+buttons) of [How to sum radio button values using either Javascript or jQuery?](/q/9796248/4642212). – Sebastian Simon Aug 14 '21 at 18:28

1 Answers1

0

You can use querySelector and the :checked pseudo-class to get the selected radio button, then add up their values:

sumUp.addEventListener('click', function(){
  var sum = +document.querySelector('[name="battery"]:checked').value + +document.querySelector('[name="year"]:checked').value;
  document.getElementById("price").innerHTML = sum;
})
<input type="radio" name="battery" class="radio" value="0" id="63" />
<label for="63">SoH 63-65%</label>
<input type="radio" name="battery" class="radio" value="100" id="66" />
<label for="66">SoH 66-67%</label>
<input type="radio" name="battery" class="radio" value="200" id="68" />
<label for="68">SoH 68-69%</label>

<input type="radio" name="year" class="radio" value="400" id="2015" />
<label for="2015">2015 year</label>
<input type="radio" name="year" class="radio" value="500" id="2016" />
<label for="2016">2016 year</label>
<button class="load-more-btn" id="sumUp">
  Sum up
</button>
<div id="price"></div>
Spectric
  • 30,714
  • 6
  • 20
  • 43