How to sum switch values ​​using javascript or jQuery?

Suppose I have 3 radio buttons with different values ​​for each radio button and one text field, which then displays the sum of each radio button that is set. Which JQuery or Javascript event should I use to sum the values ​​each time I click the switch?

Initially, my radio button has a text box next to it to display the value of the selected radio button, but I have difficulty triggering an event to summarize values ​​from text fields that change on their own (since keyup or keydown will not work in this situation).

To better explain what I want to achieve, below is an example of my work. Any help and advice would be appreciated. Thanks in advance.

PS: If you have nothing to ask about, can you also add a working sample so that I can play with the working one. Thank.

 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" />
+5
source share
2 answers

I would do it like this:

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 script example

The html structure is equal to yours, only I added a class calcso that I can easily select them.

+6
source

Suppose the radio buttons are inside the form with id = 'myForm', and the text field has id = 'totalScore', and then:

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

All Articles