2014-01-11 24 views
0

我需要自動計數(不刷新)的JavaScript/jQuery的功能,這讓我的公式算我幫助:自動計算值與的onkeyup JS/jQuery的

機會= SUM(輸入的人)*號。

問題是,這是很多領域,約100,但我需要計算每個單獨的「機會」。 這裏是代碼,要理解一個問題:

<table> 
<tr> 
    <th></th> 
    <th>Name</th> 
    <th>Number</th> 
    <th>Chance</th> 
    <th>Sum</th> 
</tr> 
<tr> 
    <td><input type="checkbox" name="check[]" value="id1" /></td> 
    <td>test1</td> 
    <td>0.5</td> 
    <td><span id="chance1" >NEED AUTO VALUE AFTER COUNTING HERE!</span></td> 
    <td><input type="text" onkeyup="some function?" name="sum1" /></td> 
</tr> 

<tr> 
    <td><input type="checkbox" name="check[]" value="id2" /></td> 
    <td>test2</td> 
    <td>0.7</td> 
    <td><span id="chance2" >NEED AUTO VALUE AFTER COUNTING HERE!</span></td> 
    <td><input type="text" onkeyup="some function?" name="sum2" /></td> 
</tr> 

<tr> 
    <td><input type="checkbox" name="check[]" value="id3" /></td> 
    <td>test3</td> 
    <td>0.9</td> 
    <td><span id="chance3" >NEED AUTO VALUE AFTER COUNTING HERE!</span></td> 
    <td><input type="text" onkeyup="some function?" name="sum3" /></td> 
</tr> 
</table> 

http://jsfiddle.net/5xch9/

回答

0

您可以使用parents方法找到有關sum輸入的相關tr行,然後查找該行內的數字和機會單元格。

$('input[name^=sum]').on("keyup", function(){ 
    var $this = $(this); 
    var $parent = $this.parents('tr'); 
    var $chance = $parent.find('.chance'); 
    var $number = $parent.find('.number');  
    $chance.text($number.text() * $this.val()); 
}); 

(緩存的不同節點(TD/span標籤)是沒有必要的,我寫了這樣的以提高可讀性)

您可以修改標記的東西,如:

<tr> 
    <td>test1</td> 
    <td class="number">0.5</td> 
    <td><span class="chance" id="chance1" >NEED AUTO VALUE AFTER COUNTING HERE!</span></td> 
    <td><input type="text" name="sum1" /></td> 
</tr> 

(添加.number.chance類可以更容易地找到行內所期望的節點)

DEMO

+0

是的,它的工作原理。萬分感謝。我沒有降低你的評價!非常感謝你。 –

0

使用jQuery你可以做這樣的事情(只是添加輸入選擇):

function keyUpHandler(e){ 
    //whatever you want to do with the keyUp 
    //e.target will contain the element 
} 
$('.inputKeyUp').on('keyup',keyUpHandler); 
0

檢查out of the following小提琴

http://jsfiddle.net/5xch9/4/

$(document).ready(function() { 

    //iterate through each textboxes and add keyup 
    //handler to trigger sum event 
    $(".txt").each(function() { 

     $(this).keyup(function() { 
      calculateSum(); 
     }); 
    }); 

}); 

function calculateSum() { 

    var sum = 0; 
    //iterate through each textboxes and add the values 
    $(".txt").each(function() { 

     //add only if the value is number 
     if (!isNaN(this.value) && this.value.length != 0) { 
      sum += parseFloat(this.value); 
     } 

    }); 
    //.toFixed() method will roundoff the final sum to 2 decimal places 
    $("#sum").html(sum.toFixed(2)); 
} 
+0

不知何故,它不工作。我已經添加onkeyup =「calculateSum()」,添加txt類來輸入元素,但它不工作:| –

+0

@EimantasGabrielius:無需添加onkeyup事件到每個textbox.jquery將處理this.Add頁面中添加jquery引用 –

+1

是的它現在工作,但我應該如何使它超過1 tr? 我嘗試: $(「#sum1」)。html(sum.toFixed(2)); $(「#sum2」)。html(sum.toFixed(2)); $(「#sum3」)。html(sum.toFixed(2)); 但不起作用 我需要使每一行都單獨計算 –