简体   繁体   中英

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.

PS: 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" />

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.

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
      })
    }
  })

Assume radio buttons are inside a form with id='myForm', and textbox has id='totalScore' then:

var sum = 0;
$("#myForm").find("input[type='radio']:checked").each(function (i, e){sum+=$(e).val();});
$("#totalScore").val(sum);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM