Mark
Mark

Reputation: 1872

Running jQuery function more than once

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

Answers (2)

Shomz
Shomz

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

Felix
Felix

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

Related Questions