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

3

6

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" />
Nottage answered 20/3, 2012 at 22:53 Comment(1)
i liked the first version of your question, so you did not have a need to edit it. But if, please do not forget to highlight code so every one can see the HTML Form elements. (using CTRL+K on selected text). My answer is written below with an example. hope it helpsKarena
K
9

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.

Karena answered 20/3, 2012 at 23:5 Comment(11)
Please do never use parseInt without the second (base) argument unless you like hunting for weird, weird bugs later on. Your 4th line should read score+=parseInt($(this).val(), 10);Lacteous
@Lacteous i changed it. i know there can be some strange behavior, but mostly not if you have no leading zeros or something like that :)Karena
You can absolutely trust that the user (OP in this case) will manage to introduce a leading 0 eventually – Murphy's law ;) Cheers!Lacteous
@Lacteous and for that i decided to change it on your comment :D Damn Murphy :P - And if you like my example now, i would be glad about an upvote ;)Karena
You can haz upboat! Also – albeit very theoretical in this case – you should consider using $('.calc').filter(':checked') instead of $(".calc:checked") for performance reasons. Gets interesting when handling thousands of DOM nodes. Background: jQuery uses native selectors whenever possible; proprietary extensions (such as :checked) render that mechanism obsolete and make jQuery use its own, slower, internal implementation.Lacteous
@Lacteous i do not think so. see this performance test - they are more or less equal :)Karena
Sheesh, you're totally right in this particular case – I completely forgot that :checked has made it into the CSS3 spec and is therefore natively supported by most modern browsers. Try your jsperf with IE8 (lacking native support for :checked) or check out this one (using jQuery's proprietary :selected selector) to see what I was talking about ;)Lacteous
@Neysor: Hello Neysor, I appreciate your immediate reply. Thank you! .Now I got my form working after implementing your function.Nottage
@Nottage no problem, then it would be great if you flag my post as solution :) just like described in the faq the last topic :)Karena
@Neysor: This a follow up question with regards to the solution you provided above. The link to the question is here https://mcmap.net/q/1193458/-how-to-round-off-parsefloat-results-in-jquery-javascript/1282076 Please enlighten me with this as I am already close to making it work 100%. Again, thanks in advance.Nottage
@Nottage nice idea to provide me this question in a comment :) I'll take a look at it.Karena
C
2

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
      })
    }
  })
Colocynth answered 26/2, 2021 at 21:11 Comment(0)
F
0

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);
Farrison answered 20/3, 2012 at 22:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.