MonsterP MonsterP - 7 months ago 24
Javascript Question

Total Price update from multiple selections using data-* attribute

so I'm trying to make a simple script that can update the total price from multiple selections. Prices are set in each option using the data-* attribute.

I manage to make it work if i put the prices in the value attribute but somehow not working using the data-price attribute to set the price.

Any help would be much appreciated.

This is the HTML:

<div class="container">
<div class="row">
<div class="col-md-6">Initial Price: <span id="thisIsOriginal" class="">$62.00</span></div>
<div class="col-md-6">Total: <span id="total">$62.00</span></div>
</div>
<div class="row">
<select class="optionPrice" name="select-1">
<option value="">Please Select</option>
<option data-price="" value="1">option a</option>
<option data-price="20.00" value="2">option b (+$20.00)</option>
</select>

<select class="optionPrice" name="select-2">
<option value="0">Please Select</option>
<option data-price="5.00" value="3">option c</option>
<option data-price="10.00" value="4">option d (+$10.00)</option>
</select>

<select class="optionPrice" name="select-3">
<option value="">Please Select</option>
<option data-price="" value="5">option e</option>
<option data-price="15.00" value="6">option f (+$15.00)</option>
</select>
</div>
</div>


and this is the JS:

$(document).ready(function() {
$('.optionPrice').change(function() {

var OriginalPrice = $('#thisIsOriginal').text();
var OriginalCurrency = OriginalPrice.substring(0, 1);
OriginalPrice = OriginalPrice.substring(1);

var total = 0;

$('.optionPrice').each(function() {
if($(this).attr('data-price') != 0) {
total += parseFloat($('option:selected',this).attr('data-price'));
}
});
var newTotal = parseFloat(OriginalPrice) + parseFloat(total);
$('#total').text('$' + newTotal.toFixed(2));
});
});


Demo here

Answer
<script>
$(document).ready(function () {
    $('.optionPrice').change(function () {
        var OriginalPrice = $('#thisIsOriginal').text().replace('Initial Price: ','');
        var OriginalCurrency = OriginalPrice.substring(0, 1);
        OriginalPrice = OriginalPrice.substring(1);
        var total = 0;
        $('.optionPrice').each(function () {
            if ($(this).find('option:selected').attr('data-price') != 0 && $(this).find('option:selected').attr('data-price') != undefined) {
                console.log($('option:selected', this).attr("data-price"));
                total += parseFloat($('option:selected', this).attr('data-price'));
            }
        });
        var newTotal = parseFloat(OriginalPrice) + parseFloat(total);
        $('#total').text('$' + newTotal.toFixed(2));
    });
});

Comments