Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum radio button values using either Javascript or jQuery?

Suppose I have 3 radio buttons with different values for each radio button and one textbox which would then display the sum of every radio button that is checked. Which Jquery or Javascript event should I use to sum up the values each time a radio button is clicked?

Originally, my radio button has a text box next to it for the purpose of displaying the value of the selected radio button but I am having difficulty firing an event to sum up the values from the text boxes that changes by itself(since keyup or keydown wont work on this given situation).

To better explain what I want to achieve, below is a sample from my work. Any help and tips would be appreciated. Thanks in advance.

P.S.: If it's not to much to ask, can you also add a working sample so I can play around with the working one. Thanks.

 Yes
<input type="radio" name="radio1" value="10" />
No
<input type="radio" name="radio1" value="0" /><br />
Yes
<input type="radio" name="radio2" value="10" />
No
<input type="radio" name="radio2" value="0" /><br />
Yes
<input type="radio" name="radio3" value="10" />
No
<input type="radio" name="radio3" value="0" /><br />
Total Score:
<input type="text" name="sum" />
like image 621
Davinchie_214 Avatar asked Mar 20 '12 22:03

Davinchie_214


2 Answers

I would do it like that:

function calcscore(){
    var score = 0;
    $(".calc:checked").each(function(){
        score+=parseInt($(this).val(),10);
    });
    $("input[name=sum]").val(score)
}
$().ready(function(){
    $(".calc").change(function(){
        calcscore()
    });
});

See this js fiddle example

the html structure is equal to yours, only i added a class calc, so that i can selected them easier.

like image 149
Neysor Avatar answered Oct 22 '22 01:10

Neysor


In pure JavaScript/EcmaScript I propose

document.addEventListener( 'DOMContentLoaded', event => {
    const text = document.getElementByTagName('sum')
    const radioElems = document.querySelectorAll('input[type="radio"]')
    radioElems.forEach((radioElem) => { radioElem.addEventListener('change', () => {
      count()
    }) })
    const count = () => {
      let score = 0
      document.querySelectorAll('input[type="radio"]:checked').forEach(radioChecked => {
        score += parseInt(radioChecked.value, 10)
        text.innerHTML = score
      })
    }
  })
like image 27
djibe Avatar answered Oct 21 '22 23:10

djibe