使用jQuery计算javascript中两个输入字段的乘积

时间:2014-10-16 23:39:15

标签: javascript jquery

我有一个输入字段,我想填充表格中较早出现的两个输入字段的乘积。

<div class="form-group">
    <label for="item_name" class="col-lg-2 control-label">Item:</label>
    <div class="col-lg-2">
        <input type="text" name="item_name[]" placeholder="Name">
    </div>
    <div class="col-lg-2">
        <input type="text" name="item_qty[]" placeholder="Quantity">
    </div>
    <div class="col-lg-2">
        <input type="text" name="item_price[]" placeholder="Price">
    </div>
    <div class="col-lg-2">
        <input type="text" name="item_total[]" placeholder="Total">
    </div>
</div>

这些输入字段可以多次出现,所以我试图遍历item_total[] arrray并将一个监听器附加到焦点事件。

$.each($("[name='item_total[]']"), function( index, value ) {
    $(this).focus(function() {
        var value = ?
        //not sure how to select the value of the two previous input fields
        // var value =  $("item_qty[index]") * $("item_price[index]");
        console.log(value);
    });
});

4 个答案:

答案 0 :(得分:1)

You can do like this

  $('input[name="item_qty[]"],input[name="item_price[]"]').on("change",function (){
    var $container = $(this).closest('.form-group');
      qty = Number($('input[name="item_qty[]"]',$container).val())||0,
      price = Number($('input[name="item_price[]"]',$container).val())||0;

    $('input[name="item_total[]"]',$container).val(qty * price);

  })

另一种解决方案从选择器开始:

  $('input[name^="item_qty"],input[name^="item_price"]').on("change",function (){
    var $container = $(this).closest('.form-group');
      qty = Number($('input[name^="item_qty"]',$container).val())||0,
      price = Number($('input[name^="item_price"]',$container).val())||0;

    $('input[name^="item_total"]',$container).val(qty * price);

  })

答案 1 :(得分:1)

以下假设由于重复行而在输入名称中有[],并且会在重复的行实例中隔离值

您可以使用form-group遍历到最近的包裹容器closest(),然后使用find()

查看该容器内的内容

我认为您想要的是将更改处理程序应用于用户输入并在更改时计算总计

$("input[name=item_qty\\[\\]], input[name=item_price\\[\\]]").change(function(){
    var $container = $(this).closest('.form-group');
    var qty = $container.find('[name=item_qty\\[\\]]') || 0;
    var price = $container.find('[name=item_price\\[\\]]') || 0;
    $container.find('[name=item_total\\[\\]]').val( qty * price );                                  

});

jQuery需要在选择器中转义特殊字符,这就是上面有\\这么多的原因。

请参阅 selectors API Docs

中的转义规则

答案 2 :(得分:0)

以下内容可行。

var quantityEl = $('input[name="item_qty[]"]'),
    priceEl = $('input[name="item_price[]"]'),
    totalEl = $('input[name="item_total[]"]')
;

var calculateTotal = function() {
    var quantity = +quantityEl.val().trim(),
        price = +priceEl.val().trim(),
        total = quantity * price
    ;

    if (!isNaN(total)) {
        totalEl.val(total);
    }     
};

priceEl.on('change keyup paste', calculateTotal);
quantityEl.on('change keyup paste', calculateTotal);

答案 3 :(得分:-2)

你可以做这样的事情

input1 = $(this).closest($("[name='item_price']")).val()

或者像这样

input1 = $("[name='item_price']")[index]).val()
相关问题