Reputation: 856
I have few individual products with an original price and each with a select dropdown and associated prices too, the original price changes based on the option selected, this is done via JQuery.
So Product 1 = 3.99, and optional addons (options from select) small = 1.50, Medium = 3.50 etc.
<p><span data-name="product_name">Addon Product</span></p>
<p data-name="product_desc">Addon product descriptions</p>
<label>Size: </label>
<select class="product-variants readers form-control input-sm" id="readers" name="product_size">
<option data-price="0" value="Small">Small</option>
<option data-price="40" value="Medium">Medium</option>
<option data-price="60" value="Large">Large</option>
</select>
<span class="price pull-left" itemprop="price" id="price">£5.99</span>
<hr/>
<p><span data-name="product_name">2nd Product</span></p>
<p data-name="product_desc">2nd Addon product description</p>
<label>Size: </label>
<select class="product-variants readers form-control input-sm" id="readers" name="product_size">
<option data-price="0" value="Small">Small</option>
<option data-price="20" value="Medium">Medium</option>
<option data-price="30" value="Large">Large</option>
</select>
<span class="price pull-left" itemprop="price" id="price">£3.99</span>
<hr/>
There will also be Product 3, 4 and so on.
The input field name, price, id, class is being populated dynamically from a database so they are same for different Items.
If one product exists then it's fine however with multiple products and its options the price for the first ID only changes. As an example if I change the select from Product 2 then the price of Product 1 changes only. How can I get it to stick to its own Product and change the price for that one only?
Here's my code and a jsfiddle
var basePrice = +($('#price').html()).replace(/[^0-9\.]+/g,"");
$(".readers").change(function() {
newPrice = basePrice;
$(".readers option:selected").each(function() {
newPrice += +$(this).attr('data-price')
});
$("#price").html("£" + newPrice.toFixed(2));
$("#new-price").val(newPrice.toFixed(2));
});
Upvotes: 0
Views: 1699
Reputation: 673
I played around with this and fixed a few issues. Your HTML was
By making them separate groups and then using jquery code to lookup the parent group and then searching for child by CLASS in that group, was able to get the functionality you were looking for.
$(".readers").change(function() {
// For each reader, need to go up to the form-groups parent to search for the price
var productParent = $(this).parent().parent();
// Need to get the base price from an attribute, otherwise it will change each time you make a selection
var newPrice = parseFloat(productParent.find('.price').attr('data-price'));
productParent.find(".readers option:selected").each(function() {
newPrice += +$(this).attr('data-price')
});
productParent.find(".price").html("£" + newPrice.toFixed(2));
});
https://jsfiddle.net/4rg0ou5e/
Upvotes: 1