Loop on ID and each function
I use the JQUERY EACH function to SUM dynamically 12 textbox values with a "txt" class with this code :
<script>
$(document).ready(function(){
//iterate through each textboxes and add ke开发者_运维百科yup
//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);
}
});
$("#sum").html(sum);
</script>
I want to create 4 subtotals computed dynamically using each only 3 textbox values. I added 4 different ID to each in my form. How can i use the function above to compute dynamically the subtotal for the current id. The spans id which gets the result are named "ID_SUM" (ID must be dynamic according to the ID value of the textbox modified) ?? Thank u very much.
i found a solution... ID is unique so it doesn't work. i used the name attribute like this :
<script>
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum($(this).attr("name"));
});
});
});
function calculateSum(groupe) {
var sum = 0;
var subtotal = 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))
$("#sum").html(sum);
$('input[name="' + groupe + '"]').each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
subtotal += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places : $("#sum").html(sum.toFixed(2))
$("#" + groupe + "_SUM").html(subtotal);
}
</script>
精彩评论