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" />
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 helps Commented Mar 20, 2012 at 23:22

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

11 Comments

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 i changed it. i know there can be some strange behavior, but mostly not if you have no leading zeros or something like that :)
You can absolutely trust that the user (OP in this case) will manage to introduce a leading 0 eventually – Murphy's law ;) Cheers!
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 ;)
@Davinchie_214 nice idea to provide me this question in a comment :) I'll take a look at it.
|
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
      })
    }
  })

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.