【问题标题】:Selecting all inputs by class, sum up their values and display the total [closed]按类选择所有输入,总结它们的值并显示总数[关闭]
【发布时间】:2014-08-02 13:22:00
【问题描述】:

我想写一个 jQuery 脚本,它可以总结给定形式的一些值。

表格如下所示:

<form>
  Product 1
  <input type="text" name="quantity[]" value="" class="quantity" placeholder="Quantity" />
  <input type="text" name="price_per_unit[]" value="" class="price_per_unit" placeholder="Price per unit" />

  Product 2
  <input type="text" name="quantity[]" value="" class="quantity" placeholder="Quantity" />
  <input type="text" name="price_per_unit[]" value="" class="price_per_unit" placeholder="Price per unit" />

  Product 3
  <input type="text" name="quantity[]" value="" class="quantity" placeholder="Quantity" />
  <input type="text" name="price_per_unit[]" value="" class="price_per_unit" placeholder="Price per unit" />

  [...]

  Product n
  <input type="text" name="quantity[]" value="" class="quantity" placeholder="Quantity" />
  <input type="text" name="price_per_unit[]" value="" class="price_per_unit" placeholder="Price per unit" />

  <input type="text" name="total_order" id="total_order" value="" readonly="readonly" />
</form>

如果用户输入值“2”作为数量,“10”作为“单价”,则总订单为“20”。

我只想在“数量”和“单价”这对填写时触发求和操作。

此外,如果用户输入了不止一种产品的数量和价格,则总订单必须是它们的总和。

稍后编辑 抱歉,到目前为止我忘了发布我的 jQuery 代码:

$(document).ready(function(){
    var total = 0;
    $('input .quantity').each(function() {
        $('input .price_per_unit').each(function() {

        });
    });
});

【问题讨论】:

  • 好吧,你想要那个。如果你付钱给他,有人会为你编码。 (包括我)但是在 Stackoverflow 提问之前,您应该先尝试一下。

标签: php jquery html forms


【解决方案1】:

第一步是将您的输入包装成能够区分它们的东西:

<div class='product'>
    <input type="text" name="quantity[]" value="" class="quantity" placeholder="Quantity" />
    <input type="text" name="price_per_unit[]" value="" class="price_per_unit" placeholder="Price per unit" />
</div>

这将允许我们绑定到 .product 中的输入对

现在我们绑定 jQuery:

$("body").on("keyup change", ".product input", function() {
    var me = $(this);
    var other = me.parent(".product").find("input").not(me);
    if(other.val() != "") {
        var total = me.val() * other.val();
        //do something with total
        console.log(total);
    }        
});

这是一个小提琴:http://jsfiddle.net/U9CWL/3/

然后,您将获取总计并将其显示在某处,并将其值添加到总计中。您可以考虑将字段更改为“数字”类型 - 现代浏览器将根据您的字段设置仅允许整数(浮点)数字。

【讨论】:

  • 谢谢,Ben,但对于每件数量和价格超过一对的情况,恐怕它无法正常工作。
  • 您是否单独包装了元素? - 每对输入一个产品包装器?我已经将小提琴更新为拥有两个“产品”,打开控制台并进行测试。我看到了我所理解的预期结果。
  • 我修改了你的小提琴http://jsfiddle.net/U9CWL/7/,我得到了ReferenceError: total is not defined
猜你喜欢
  • 2015-01-06
  • 2019-01-05
  • 2019-07-29
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
  • 2013-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多