Reputation: 18520
I have pages with varying numbers of radio buttons. These buttons have two different classes, yes
, and no
. As the user goes down the page, I need to figure out how many of each class they have selected, and display it in a <p>
at the bottom of the page.
I'm having problems preventing 1 getting added to the variable when a user clicks on a radio button more than once. Here's a JS fiddle with my code:
It's not working at all for some reason, and I don't see why.
Upvotes: 3
Views: 10856
Reputation: 34168
You should use the change event I think instead of the click event.
$('input:radio').change(function(){
$('.yes_results').text($('input.yes:radio:checked').length)
$('.no_results').text($('input.no:radio:checked').length)
});
NOTE: Use the input:radio
form over the :radio
selector for speed which avoids a global search of the dom, limiting it to only the input elements.
Please limit the id to singular: RadioGroup1_1
is a duplicate id.
Note: I used the class to count, you could use the checked
property but I think the class will be faster based on other performance related questions/answers on SO.
Upvotes: 0
Reputation: 9570
Here is what I would change it to
$(document).ready(function() {
var nos = 0;
var yeses = 0;
$(".no").click(function() {
if($('.no').is(':checked')) {
nos = nos + 1;
alert(nos);
}
});
$(".yes").click(function() {
if($('.yes').is(':checked')) {
yeses = yeses + 1;
alert(yeses);
}
});
});
Upvotes: 0
Reputation: 2189
Rather than increment the values when one is clicked, do a count:
$('input.yes:checked').length
$('input.no:checked').length
Upvotes: 0
Reputation: 97672
I would use the change event and find the number of checked boxes each time.
$(".no,.yes").change(function() {
$('.yes_results').text($('.yes:checked').length);
$('.no_results').text($('.no:checked').length);
});
Upvotes: 0