简体   繁体   English

在文本框中更改值时,通过jQuery计算每一行的总和

[英]Calculate sum each row by jQuery when changing value in textbox

On keyup of quantity textbox, the price was changed. 在“数量”文本框键入时,价格已更改。 But sub total div doesn't change the value​, only if I refresh a page. 但是sub total div不会改变值,只有当我刷新页面时。

Any idea how to calculate sum of each row and change in subtotal div in jquery please. 任何想法如何计算每一行的总和并改变jquery中的subtotal div。

Thanks. 谢谢。

在此处输入图片说明在此处输入图片说明

Have a class assigned to all textfields that you want to consider for subtotal, and listen for change on those textfields and compute subtotal on change. 为您要考虑小计的所有文本字段分配一个类,并在这些文本字段上侦听更改,并在更改时计算小计。 Here is a jsfiddle for the same http://jsfiddle.net/ravikumaranantha/Sb6zS/3/ 这是同一http://jsfiddle.net/ravikumaranantha/Sb6zS/3/的jsfiddle

<table>
    <tr>
        <td>Product 1</td>
        <td>
            <input class="quantity" type="text" value="10" />
            <input class="price" type="hidden" value="20" />
        </td>
        <td>$20</td>
    </tr>
    <tr>
        <td>Product 1</td>
        <td>
            <input class="quantity" type="text" value="20" />
            <input class="price" type="hidden" value="40" />
        </td>
        <td>$40</td>
    </tr>
</table>
<div class="subtotal"></div>


$('.quantity').on('change', function(){

    var subtotal = 0;
    $('.quantity').each(function(){
        var $this = $(this);
        var quantity = parseInt($this.val());
        var price = parseFloat($this.siblings('.price').val())
        subtotal+=quantity*price;
    })
    $('.subtotal').text(subtotal);

})
$('.quantity').trigger('change')

i just quickly write a simple http://jsfiddle.net/player889/3PRZr/ . 我只是快速编写了一个简单的http://jsfiddle.net/player889/3PRZr/ Hope this may help you 希望这对您有帮助

$(function() {
  $('#B').bind('keyup', function() {
    $('#b').text ($('#B').val() *6) ;
}).keyup(function(){
    $("#subtotal").text( $('#A').val() *5 + $('#B').val() *6);
});

$('#A').bind('keyup', function() {
    $('#a').text ($('#A').val() *5) ;
  }).keyup(function(){
    $("#subtotal").text( $('#A').val() *5 + $('#B').val() *6);
 });
});

A : <input type="text" id="A"/> x5 
<div id="a"></div>
B : <input type="text" id="B"/> x 6
<div id="b"></div>
sum: <div id="subtotal"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM