将同一行上复选框的值与同一行上的文本字段的值相加

将同一行上复选框的值与同一行上的文本字段的值相加

本文介绍了Jquery:将同一行上复选框的值与同一行上的文本字段的值相加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些需要总结的值的复选框。当复选框被选中时,值被添加到数组中并显示。以下是演示链接:
但是,当我进入一个新行时,它会继续总结我的值,而不是重新开始清空行更改中的数组。HTML代码很长,请在提供的链接中查看它。



这里是jquery代码总结:

  var total_array = new Array(); 
var total_amount = 0;
$(#dailyexpense input [type = checkbox]:checked).live('change',function(){

var check_id = $(this).attr('id ');
var valu = $(this).val();
$(#tdtotals input [type = text])。each(function(){
totals_id = $ (this).attr('id');
if(totals_id == check_id){
total_array.push(valu);
total_amount = eval(total_array.join('+') ).toFixed(2);
$(this).val(total_amount);
}

});
});

所有帮助将不胜感激



PS :但是,在jsfiddle中编辑代码并扭曲一切,停止它。

解决方案

试试这个:



基本上我们重新思考结构。如果复选框的值发生变化,我们会得到它的父行。然后我们找到该行中的所有复选框。

  // watch复选框
$('tr input [type = checkbox]' ).change(function(){
var total = 0;
//所有同级复选框
$(this).parents('tr')。find('input [type = ()函数(){
total + = parseInt($(this).val());
});

//显示('tr')。find('input [type = text]:last')。val(total);
});


I have some checkboxes with values which need sum up. When the checkboxes are checked the values get added in an array and displayed. Here is a demo link: http://jsfiddle.net/maxwellpayne/gKWmB/However when I go to a new row it continues summing my values instead of starting afresh emptying the array on row change.The HTML code is long so please view it at the link provided.

Here is the jquery code summing them up:

var total_array = new Array();
var total_amount = 0;
$("#dailyexpense input[type=checkbox]:checked ").live('change', function() {

    var check_id = $(this).attr('id');
    var valu = $(this).val();
    $("#tdtotals input[type=text]").each(function() {
        totals_id = $(this).attr('id');
        if (totals_id == check_id) {
            total_array.push(valu);
            total_amount = eval(total_array.join('+')).toFixed(2);
            $(this).val(total_amount);
        }

    });
});

All help will be appreciated

PS: However is editing the code in jsfiddle and distorting everything, stop it.

解决方案

Try this:

http://jsfiddle.net/gKWmB/3/

Basically we rethink the structure. If a checkbox value changes we get its parent row. Then we find all checkboxes in that row. Finally we total them and display.

//watch checkboxes
$('tr input[type=checkbox]').change( function(){
  var total = 0;
  //total all sibling checkboxes
  $(this).parents('tr').find('input[type=checkbox]:checked').each( function() {
    total += parseInt($(this).val());
  });

  //display the result
  $(this).parents('tr').find('input[type=text]:last').val(total);
});

这篇关于Jquery:将同一行上复选框的值与同一行上的文本字段的值相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 01:32