Reputation: 1872
I want to run this jQuery function every time a checkbox is checked, at the moment it will only work the first time I check a box, the next box that is checked will do nothing, and so on.
Here is my jQuery:
$('#check').change(function () {
var price = $(this).data('price');
var currPrice = $('.pricedisplay').data('price');
$('.pricedisplay').text(price + currPrice);
});
and a checkbox:
<input type="checkbox" id="check" name="check-1" data-price="50">
I will eventually have hundreds of checkboxes so I can't make seperate functions for each one.
Thanks in advance, I'm new to jQuery.
Upvotes: 0
Views: 334
Reputation: 37711
You issue is with duplicate IDs - each ID on the page needs to be unique. This causes jQuery event to trigger only on the first element with that ID it finds.
Use classes instead and your code will work fine.
Upvotes: 1
Reputation: 38112
id
is unique, you can use class instead:
<input type="checkbox" class="check" name="check-1" data-price="50">
then you can do:
$('.check').change(function () {
var price = $(this).data('price');
var currPrice = $('.pricedisplay').data('price');
$('.pricedisplay').text(price + currPrice);
});
Upvotes: 2