LT86
LT86

Reputation: 655

How do I dynamically update total price with jquery?

I have this jsFiddle which is working quite nicely, I'm trying to calculate total price of a product using jQuery and select boxes.

I have one issue however, when the second select option of 'black widow' is selected, the data-value is updated depending on what is selected in the first select box.

data-value is 100 (when 1x12 cabinet is selected)
data-value is 200 (when 2x12 cabinet is selected)
data-value is 400 (when 4x12 cabinet is selected)

This is all updating correctly (I have checked in Chrome Inspect and the data-value is updating), however, once the black widow option has been selected once, the total price refuses to dynamically update.

Can anyone please clarify why this is? Is there a way to re-load the updateTotal variable everytime a option is changed? I assumed this is what it was doing but clearly not.

Here is my js:

//Calculate Total Price
    $("select[name='options']").change(function() { 
        updateTotal(); 
    });

//Function for price calculator
function updateTotal() {
    var newTotal = 0;
    $("select[name='options'] option:selected").each(function() {
        newTotal += parseFloat($(this).data('value'));
    });
    $(".total").text(newTotal);
}

thanks!

Upvotes: 0

Views: 3307

Answers (1)

Brewal
Brewal

Reputation: 8189

Change this :

$(".widow").attr('data-value', price[$(this).val()]);

To this :

$(".widow").data('value', price[$(this).val()]);

See the updated Fiddle

Upvotes: 1

Related Questions