簡體   English   中英

如果選中復選框,則使用jquery獲取數字的總和

[英]Using jquery to get the sum of numbers if checkbox is checked

我有桌子 每行都有一個復選框和一個數字。 該數字在一個類的范圍內。

如果選中此復選框,則我希望將數字與選中的行中的所有其他數字相加。 這是該行的樣子。

 <td><input class="box" type="checkbox" name="selclips[]" value="1234"></td><td><span class="amount">45.00</span></td>
 <td><input class="box" type="checkbox" name="selclips[]" value="1235"></td><td><span class="amount">65.00</span></td>

然后在底部,我有:

 <td>Total</td><td><div id="total"></div></td>

因此,需要有關JS或jquery的幫助以將這些美元金額與span標簽相加,如果在該行中選中了該復選框,則可以提供總計? 因此,在上面的示例中,如果同時選中了兩個框,則腳本將合計45.00和65.00並將總計110放入Total div中。 另外,如果我取消選中這些框,則金額也應更改。

非常感謝任何人都能提供的幫助。 我真的很感激!

你需要類似的東西

現場演示

$('.box').change(function(){
   var total = 0;
   $('.box:checked').each(function(){
        total+=parseFloat($(this).parent().next('td').find('.amount').text());
   });
   $('#total').text(total);
});

相當簡單..

$(function(){

    $( ".box" ).on( "click", function(){
        console.log($(this).next().html());
        var total = 0;
        $('.box:checked').each(function(){
         total += parseFloat($(this).next().html());
        });
        $("#total").text('Total is : ' + total);
    });

});

這有效..

http://jsfiddle.net/hqR2r/2/

嘗試這個:

 var total = 0;
$('.box').click(function(){
    if($(this).prop('checked')){
      total += Number($(this).closest('tr').children('td:last-child').text());
  }
    else{
      total -= Number($(this).closest('tr').children('td:last-child').text());
    }
  $('#total').text(total);
});

這是JSFIDDLE

這也許嗎?

var total = 0,
    $totalEl = $('.total');

$('.box:checkbox').click(function () {
    total += (this.checked? 1 : -1) * +this.parent('td').next().children('.amount').text();
    $totalEl.text(total);
});
var total =  Array.prototype.slice.call($('input.box:checkbox:checked'), 0) // changes jQuery object to array of DOM elements
    .reduce(function(a, b) { // calls reduce method
        return a + Number(b.value);
    }, 0);

簡單快捷。

reduce方法文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM