Reputation: 75
I am trying to have a function add the values of selected check boxes and radio buttons. I have created a function that can add the values of the check boxes and a function for the radio buttons but am having trouble combining the two into one working function. I think my issue is with having both radio and checkbox elements associated with the .click()
My code can be seen here: https://jsfiddle.net/Buleria28/nz43u7x8/2/
The HTML is:
<input type="checkbox" value="1" />test 1<br/>
<input type="checkbox" value="2" />test 2<br/>
<input type="checkbox" value="3" />test 3<br/>
<input type="radio" name="test" value="1" />test 4
<input type="radio" name="test" value="2" />test 5
<div id='sum'></div>
The jQuery is:
jQuery(document).ready(function($) {
var sum = 0;
$("input:checkbox"),$("input:radio").click(function() {
sum = 0;
$("input:checkbox:checked").each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
sum = 0;
$("input:radio:checked").each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
$('#sum').html(sum);
});
});
Upvotes: 0
Views: 840
Reputation: 12181
Here you go with the solution https://jsfiddle.net/nz43u7x8/5/
jQuery(document).ready(function($) {
var sum = 0;
$("input:checkbox, input:radio").click(function() {
sum = 0;
$("input:checkbox:checked").each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
$("input:radio:checked").each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
$('#sum').html(sum);
});
});
Upvotes: 1
Reputation: 57964
You're actually using the comma operator and only adding the event handler to the second jQuery object. Instead combine the actual selectors by using a comma in the jQuery constructor's first argument, similar to a CSS selector:
$("input:checkbox, input:radio").click(function() {
…
});
Upvotes: 2