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" />
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.
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
})
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With