You need to enable JavaScript to run this app. jQuery表单价格同步:支持输入变更、提交校验后及页面加载更新
优惠活动
大模型
产品
解决方案
定价
更多

jQuery表单价格同步:支持输入变更、提交校验后及页面加载更新

表单价格联动更新功能需求说明

目前已实现商品价格随表单输入值变动的基础更新能力,当前存在待优化点:表单提交环节执行错误校验逻辑完成后,需要重新触发价格更新函数完成全量重算,需保障以下场景下的价格计算准确性:

  • 修改某商品输入框的数量值(如从默认的1改为其他数值)时,同步更新该商品条目对应的单行价格
  • 单行价格变动后,同步计算并更新页面底部的商品小计、含运费的总价
  • 页面重载场景下,所有价格可基于输入框的当前值完成正确初始化

页面结构代码(HTML)

<form action="" method="post">
  <h2>Products</h2>
  <div class="form-product">
    <div class="fields update-price">
      <div>
        <h3>Product 1</h3>
      </div>
      <div class="quantity update-quantity">
        <label for="utreat">Quantity</label>
        <input type="number" name="product1" id="product1" min="1" value="1" data-price="850">
        <p class="price">£<span>850.00</span></p>
      </div>
    </div>
  </div>
  <div class="form-product">
    <div class="fields update-price">
      <div>
        <h3>Product 2</h3>
      </div>
      <div class="quantity update-quantity">
        <label for="utreat">Quantity</label>
        <input type="number" name="product2" id="product2" min="1" value="1" data-price="110">
        <p class="price">£<span>110.00</span></p>
      </div>
    </div>
  </div>
  <div class="form-product">
    <div class="fields">
      <div>
        <h3>不可修改数量的商品</h3>
      </div>
      <div class="quantity">
        <label for="pack">Quantity</label>
        <input type="text" name="pack" id="pack" min="1" max="1" value="1" disabled>
      </div>
    </div>
  </div>
  <h2>Price</h2>
  <p class="sub">Sub-Total: £<span>2064.50</span></p>
  <p>Shipping: £12.00</p>
  <p class="total">Total: £<span>2076.50</span></p>
</form>

现有交互逻辑代码(jQuery)

$(function() {
    var shipping = 12;

    $('.update-quantity input').on('keyup mouseup', function() {
        updateQuantity(this);
    });

    function recalculateCart() {
        var subtotal = 0;
        $('.form-product .update-price').each(function() {
            subtotal += parseFloat($(this).children('.update-quantity').find('span').text());
        });

        var total = subtotal + shipping;
        $('.sub span').text(subtotal.toFixed(2));
        $('.total span').text(total.toFixed(2));
    }

    function updateQuantity(quantity) {
        var product = $(quantity).parent().parent();
        var price = parseFloat($(quantity).data('price'));
        var quantity = $(quantity).val();
        var linePrice = price * quantity;

        product.children('.update-quantity').each(function() {
            $(this).find('span').text(linePrice.toFixed(2));
            recalculateCart();
        });
    }
});

内容的提问来源于stack exchange,提问作者generalcb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.08 17:45:06