Jquery单独的多选选项在变化时更新价格



我有几个具有原始价格的单个产品,每个产品都有一个选择下拉列表和相关价格,原始价格会根据所选选项而变化,这是通过 JQuery 完成的。

所以产品 1 = 3.99,可选插件(选择中的选项)小 = 1.50,中 = 3.50 等。

<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">&pound;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">&pound;3.99</span>
<hr/>

还将有产品3,4等。

输入字段名称、价格、id、类是从数据库中动态填充的,因此它们对于不同的项目是相同的。

如果存在一个产品,那么可以,但是对于多个产品及其选项,第一个ID的价格只会发生变化。例如,如果我更改产品 2 的选择,则产品 1 的价格仅更改。我怎样才能让它坚持自己的产品并只更改该产品的价格?

这是我的代码和一个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("&pound;" + newPrice.toFixed(2));
      $("#new-price").val(newPrice.toFixed(2));
    });

我玩了一下并修复了一些问题。 您的 HTML 是

  1. 缺少多个结束标记
  2. 将第二个产品嵌入到第一个产品组中

通过将它们设置为单独的组,然后使用 jquery 代码查找父组,然后按该组中的 CLASS 搜索子组,能够获得您正在寻找的功能。

$(".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("&pound;" + newPrice.toFixed(2));
});

https://jsfiddle.net/4rg0ou5e/

最新更新