Hope you're doing well.
I'm building an E-commerce website. Each product has several attributes and every attribute value has its own price that will be added to the original price.
For Example: product price = 25$, the selected attribute color has values of 'red' price= 5$, and selected width = 16 inch with price = 7$
In product details page, the customer has to select each attribute value before adding the product to the shopping cart.
I'm trying to calculate the total product price with selected attributes values prices.
Here's The Code :
<var class="price h3 text-success">
<span class="currency">{{ config('settings.currency_symbol') }}</span>
<span class="num" id="productPrice">{{ $product->price }}</span>
</var>
@foreach($attributes as $attribute)
<dt>{{$attribute->name }}: </dt>
<dd>
<select class="form-control form-control-sm option" style="width:180px;" name="{{ strtolower($attribute->name) }}">
<option data-price="0" value="0"> select {{ $attribute->name }}</option>
@foreach($attributeValues as $attributeValue)
@if ($attributeValue->attribute_id == $attribute->id)
<option
data-price="{{ $attributeValue->price }}"
value="{{ $attributeValue->value }}"> {{ ucwords($attributeValue->value . ' +'. $attributeValue->price) }}
</option>
@endif
@endforeach
</select>
</dd>
@endforeach
Jquery:
<script>
$(document).ready(function () {
$('#addToCart').submit(function (e) {
if ($('.option').val() == 0) {
e.preventDefault();
alert('Please select an option');
}
});
$('.option').change(function () {
$('#productPrice').html("{{ $product->sale_price != '' ? $product->sale_price : $product->price }}");
let extraPrice = $(this).find(':selected').data('price');
let price = parseFloat($('#productPrice').html());
let finalPrice = (Number(extraPrice) + price).toFixed(2);
$('#finalPrice').val(finalPrice);
$('#productPrice').html(finalPrice);
});
});
</script>
Where's the problem ?
The problem I have is in the jquery script, only the last selected attribute price is added to the original price .
What do I want to do ?
I want to sum all the selected attributes values prices to the original price by doing foreach loop for each related attribute to this product using jquery.
Like this :
original_price = 25$;
red_color = 5$;
screen_size = 7$;
total_price = original_price + red_color + screen_size;