Reputation: 23
after having done some research, I seek you for some jquery math help.
I would like to change a textfield, which states the price of a product, through "option rel="
I put the html code here: http://jsfiddle.net/YjLM7/
So if the select list states:
<option selected="selected" rel="price-" value="0">50 x 50 cm</option>
The standard price is shown.
if I change the select list to:
<option rel="price-100" value="1">100 x 100 cm</option>
The price should increase by 100 (and go back -100, if first option is selected).
Would apreciate your help!
Here the full code:
<select>
<option selected="selected" rel="price-" value="0">50 x 50 cm</option>
<option rel="price-100" value="1">100 x 100 cm, Price add: € 100,00</option>
</select>
<p>Price</p>
<p><strong>200 €</strong></p>
<form method="post" action="catalog/category-1/product-1.html">
<input type="hidden" value="" name="productid">
<input type="submit" class="button" value="Add to cart" name="addcart">
</form>
Upvotes: 2
Views: 1596
Reputation: 12815
See this jsfiddle.
<select>
<option data-price="" selected="selected" value="0">50 x 50 cm</option>
<option data-price="100" value="1">100 x 100 cm, Price add: € 100,00</option>
</select>
<p>Price</p>
<p><strong data-price="200">200 €</strong></p>
<form method="post" action="catalog/category-1/product-1.html">
<input type="hidden" value="" name="productid">
<input type="submit" class="button" value="Add to cart" name="addcart">
</form>
and JS:
$("select").change(function(){
var price = parseFloat($(this).find("option:selected").data("price"));
if(isNaN(price))
price = 0;
var currPrice = parseFloat($("strong").data("price"));
$("strong").text(currPrice + price + ' €');
})
Upvotes: 0
Reputation: 92983
I would suggest a different approach: putting the actual price of the item in a data-
attribute of the option
, and altering the text displayed by that option
depending on what is selected. This will lend itself to more flexibility if your dropdown has more than one option.
HTML:
<select class="item">
<option selected="selected" data-price="200">50 x 50 cm</option>
<option data-price="300">100 x 100 cm</option>
<option data-price="400">150 x 150 cm</option>
</select>
JS:
$('.item').each(function(i,sel) {
var $sel = $(sel);
$sel.find('option').each(function(j,opt) {
var $opt = $(opt),
optprice = $opt.data('price'),
selprice = $sel.find('option:selected').data('price'),
diff = optprice - selprice,
diffaddsubtr = (diff > 0) ? "- add" : (diff < 0) ? "- subtract" : "",
diffamount = Math.abs(diff) || "";
$opt.find('.diffaddsubtr').text(diffaddsubtr).end()
.find('.diffamount').text(diffamount);
});
});
http://jsfiddle.net/mblase75/YjLM7/5/
Upvotes: 1