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" />
Neysor
  • 3,893
  • 11
  • 34
  • 66
Davinchie_214
  • 155
  • 2
  • 2
  • 6
  • 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 helps – Neysor Mar 20 '12 at 23:22

3 Answers3

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.

Neysor
  • 3,893
  • 11
  • 34
  • 66
  • 1
    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);` – vzwick Mar 20 '12 at 23:38
  • @vzwick i changed it. i know there can be some strange behavior, but mostly not if you have no leading zeros or something like that :) – Neysor Mar 20 '12 at 23:42
  • 1
    You can absolutely trust that the user (OP in this case) *will* manage to introduce a leading `0` eventually – Murphy's law ;) Cheers! – vzwick Mar 20 '12 at 23:46
  • @vzwick 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 ;) – Neysor Mar 20 '12 at 23:49
  • 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. – vzwick Mar 20 '12 at 23:52
  • @vzwick i do not think so. [see this performance test](http://jsperf.com/filter-vs-css-selector) - they are more or less equal :) – Neysor Mar 21 '12 at 00:02
  • 1
    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.](http://reference.sitepoint.com/css/pseudoclass-checked) Try your jsperf with IE8 (lacking native support for `:checked`) or check out [this one](http://jsperf.com/filter-vs-css-selector/5) (using jQuery's proprietary `:selected` selector) to see what I was talking about ;) – vzwick Mar 21 '12 at 00:31
  • @Neysor: Hello Neysor, I appreciate your immediate reply. Thank you! .Now I got my form working after implementing your function. – Davinchie_214 Mar 21 '12 at 11:25
  • @Davinchie_214 no problem, then it would be great if you flag my post as solution :) just like [described in the faq](http://stackoverflow.com/faq#howtoask) the last topic :) – Neysor Mar 21 '12 at 11:28
  • @Neysor: This a follow up question with regards to the solution you provided above. The link to the question is here http://stackoverflow.com/q/9930421/1282076 Please enlighten me with this as I am already close to making it work 100%. Again, thanks in advance. – Davinchie_214 Mar 29 '12 at 18:52
  • 1
    @Davinchie_214 nice idea to provide me this question in a comment :) I'll take a look at it. – Neysor Mar 29 '12 at 18:55
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
      })
    }
  })
djibe
  • 2,753
  • 2
  • 17
  • 26
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);
Diego
  • 18,035
  • 5
  • 62
  • 66