How to sum radio button values using either Javascript or jQuery?
Solution 1
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.
Solution 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
})
}
})
Davinchie_214
Updated on June 13, 2022Comments
-
Davinchie_214 almost 2 years
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" />
-
vzwick about 12 yearsPlease do never use
parseInt
without the second (base) argument unless you like hunting for weird, weird bugs later on. Your 4th line should readscore+=parseInt($(this).val(), 10);
-
Neysor about 12 years@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 :)
-
vzwick about 12 yearsYou can absolutely trust that the user (OP in this case) will manage to introduce a leading
0
eventually – Murphy's law ;) Cheers! -
Neysor about 12 years@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 ;)
-
vzwick about 12 yearsYou 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. -
Neysor about 12 years@vzwick i do not think so. see this performance test - they are more or less equal :)
-
vzwick about 12 yearsSheesh, 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 about 12 years@Neysor: Hello Neysor, I appreciate your immediate reply. Thank you! .Now I got my form working after implementing your function.
-
Neysor about 12 years@Davinchie_214 no problem, then it would be great if you flag my post as solution :) just like described in the faq the last topic :)
-
Davinchie_214 about 12 years@Neysor: This a follow up question with regards to the solution you provided above. The link to the question is here stackoverflow.com/q/9930421/1282076 Please enlighten me with this as I am already close to making it work 100%. Again, thanks in advance.
-
Neysor about 12 years@Davinchie_214 nice idea to provide me this question in a comment :) I'll take a look at it.