2013-05-15 50 views
1

我有一個表,它允許用戶做一些選擇,並輸入一些數字,然後將其用於自動計算總量。我最近添加了一些功能來向表中添加額外的行,並允許用戶在需要時刪除行。使用Javascript - 刪除錶行也重新計算總計

我需要刪除按鈕也迫使總數的重新計算在同一時間,而目前它只是刪除該行並離開原來的總數,該總數現在是不正確。

這裏是我的腳本刪除錶行:

$(window).load(function(){ 
//Sum Table Cell and Map 

$('#lastYear') 
    .on('change', 'select', calc) 
    .on('keyup', 'input', calc); 

function calc(){ 

    $('#lastYear tr:has(.risk)').each(function(i,v){ 

     var $cel = $(v.cells); 

     var $risk = $cel.eq(1).find('option:selected').val(); 
     var $numb = $cel.eq(2).find('input').val(); 
     var $weeks = $cel.eq(3).find('input').val(); 
     var $avg = ($numb * $weeks)/52; 
     var $avgRounded = Math.round($avg * 10)/10; 

     $cel.eq(4).find('input').val($avgRounded); 

    }); 

    var tot = {high:0,moderate:0}; 

    $('#lastYear tr:has(.risk) option:selected') 
       .map(function(i){ 
        var el = $(this).val(); 
        var qty = parseFloat(
$('#lastYear tr:has(.risk)').eq(i).find('td:last') 
    .prev().prev() // call prev method twice 
    .find('input').val() 
); 

        if (!tot.hasOwnProperty(el)) { 
         tot[el] = 0;    
        } 
        tot[el] += qty 
        return tot; 
       }).get(); 

    // console.log(tot); 
    $('#textfield4').val(tot.moderate.toFixed(1)); 
    $('#textfield5').val(tot.high.toFixed(1)); 

    } 
});//]]> 

和這裏的,做計算腳本:

$('#lastYear').on('click', '.delbtn', function() { 
    $(this).closest('tr').remove() 
}); 

var newIDSuffix = 2; 
$('#lastYear').on('click', '.addbtn', function() { 
    var thisRow = $(this).closest('tr')[0]; 
    $(thisRow).find('.delbtn').show(); 

    var cloned = $(thisRow).clone(); 
    cloned.find('input, select').each(function() { 
     var id = $(this).attr('id'); 
     id = id.substring(0, id.length - 1) + newIDSuffix; 
     $(this).attr('id', id); 
    }); 

    cloned.insertAfter(thisRow).find('input:text').val(''); 
    cloned.find('.delbtn').hide(); 
    cloned.find("[id^=lastYearSelect]") 
    .autocomplete({ 
     source: availableTags, 
     select: function (e, ui) { 

      $(e.target).val(ui.item.value); 
      setDropDown.call($(e.target)); 
     } 
    }).change(setDropDown); 

    $(this).remove(); 
    newIDSuffix++; 
}); 

我設置一個工作jsFiddle這可能有助於解釋這是怎麼回事。

我是新來的Javascript但對我來說,它看起來像我不知需要刪除功能與計算功能不知何故結合?

回答

1

你只需要調用calc().delbtn單擊處理程序。該calc功能和刪除按鈕單擊處理程序是目前不同的情況下......但如果他們在相同的範圍內(它們移動到相同的文件和相同onload塊),你會被罰款。

我已經更新您的jsfiddle證明http://jsfiddle.net/6KPxq/2/

+0

非常感謝你 - 完美的作品。非常感激。 – user982124

1

試試這個

$('#lastYear').on('click', '.delbtn', function() { 
    $(this).closest('tr').remove(); 
    calc(); 
});