-3

大家好,我只是想问一下如何使用 jquery 执行自动计算?例如,如果我有 3 个文本框。文本框 1 用于数量,文本框 2 用于价格,文本框 3 用于结果。当用户在文本框 1 和文本框 2 中输入值时,文本框 3 将自动求解计算(价格 * 数量)。如果用户这就是所有的家伙,我希望你能帮助我。谢谢。

这是我的html代码。

<tr>
   <td><input type='text' name='qty' id='qty' value='' />
   <td><input type='text' name='price' id='price' value='' />
   <td><input type='text' name='total' id='total' value='' />
</tr>

在javascript中如何执行计算?

4

3 回答 3

4

处理输入更新事件的最佳方式是使用jQuery.on('input',...). 您可以使用parseFloatandparseInt从其他输入中获取值,toFixed以确保最终值看起来像货币(如果不需要,将其删除),并提供 0 的后备以防无法解析。

$('#qty, #price').on('input',function() {
    var qty = parseInt($('#qty').val());
    var price = parseFloat($('#price').val());
    $('#total').val((qty * price ? qty * price : 0).toFixed(2));
});

JSFiddle 演示

于 2013-08-15T02:52:46.360 回答
0

在这件事上,你需要给你的 textbox1 和 textbox2 一个(“Comp”)类名 Ex:

<input type="text" name="textbox1" class="Comp">
<input type="text" name="textbox2" class="Comp">

然后这将是脚本:

$(document).ready(function(){
    $(".Comp").change(function(){
        var total = 0.00;
        var textbox3= 0.00;    // this gonna be your third textbox
        $(".Comp").each(function(){
            total += parseFloat(this.value);
        });
        textbox3= $("#textbox3").val((total).toFixed(2));

    });
}); 

注意:只需编辑适合您需要的计算。这个只添加了两个文本框(textbox1 和 textbox2)

于 2013-08-15T02:37:30.173 回答
0

你必须给你的文本框一个类名,然后遍历那个类并添加它们的值。

假设这是您的文本字段

<input type="text" class="row-total">

这就是你把它们加起来的方式

var total = 0;
$.each(".row-total", function(){
 total += $(this).val()
});
于 2013-08-15T02:25:40.240 回答