1

I want to auto sum the rows in html and then display the result by using jQuery I tried but I failed, bellow are my sample codes which are using loop

<html>
<head>
<title></title>
    
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js" /></script>
    
    

<script>
$.fn.fonkTopla = function() {
var toplam = 1;
this.each(function() {
   var deger = fonkDeger($(this).val());
   
   //get the data attr value
   var diff = $(this).data('diff');
   var Quantity_val = $(this).closest('tr').find('.Quantity').val();
   var QuantityBack_val = $(this).closest('tr').find('.QuantityBack').val();
   var UnitPrice_val = $(this).closest('tr').find('.UnitPrice').val(); 
   
   var paid_val = $(this).closest('tr').find('.paid').val();
   
   //On based on data attribute, if the input field is paid, do not multiply,
   if(!diff){
   //toplam *= deger;
   toplam= (Quantity_val * UnitPrice_val);
   
   //take the result minus paid field
   total = (toplam) - paid_val-(QuantityBack_val * UnitPrice_val);
   }
});
return total;
};


function fonkDeger(veri) {
    return (veri != '') ? parseInt(veri) : 1;
}

$(document).ready(function(){
$('input[name^="fiyat"]').bind('keyup', function() {

   //for multiple tr, get the closest tr field value to calculate and display
   $(this).closest('tr').find('.toplam').html( $(this).closest('tr').find('input[name^="fiyat"]').fonkTopla());
});
});
</script>

</head>
<body>




<?php
for($counter1=0;$counter1<=2;$counter1++)
{
?>
<table>
<?php
for($counter2=0;$counter2<=2;$counter2++)
{
?>
<tr>
<td><input type="number" name="fiyat[]" class="Quantity" /></td>
<td><input type="number" name="fiyat[]" data-diff="true"  class="QuantityBack" /></td>
<td><input type="number" name="fiyat[]" class="title UnitPrice" value="500" /></td>
<td><input type="number" name="fiyat[]" data-diff="true"  class="paid" /></td>
<td style="text-align:right" bgcolor="#FF5733"><span class="toplam"></span>
</tr>


<?php
}
?>
</table>
<?php
}
?>

<!--I NEED TO CALCULATE SUB TOTAL OF EACH TABLE IN LOOP IN BELOW CODES, I NEED SUB TOTAL UNDER LAST RED COLUMN-->
<script>
var totalRow = '', columnNo = $('table tr:first td').length;

for (var index = 0; index < columnNo; index++) {
    var total = 0;
    $('table tr').each(function () {
        total += +$('td', this).eq(index).text(); //+ will convert string to number
    });
    totalRow += '<td>' + total + '</td>';
}

$('table').append('<tr>' + totalRow + '</tr>');
</script>
<!--end of jQuery used to auto sum subtotal-->




</body>
</html>

The problem is in jQuery which makes Total (that jQuery is located at bottom of the codes) Please anyone can help us to accomplish this task. I need only the sub total of each table in loop but in red column. Thank you

8
  • Your code is working run when i run it Commented Jun 27, 2020 at 9:12
  • Only thing is i can't see when you run calc_total() Commented Jun 27, 2020 at 9:13
  • I don't get total, I do know why because I'm not good in jQuery. Can you please help me to get it? Thank you Commented Jun 27, 2020 at 18:20
  • take a look here jsfiddle.net/f5qwya31 Commented Jun 27, 2020 at 18:23
  • Thank you, but I have another problem here, in <td bgcolor="#FF5733"><span class="toplamc">12</span>USD</td> I don't have static value like 12, 14, 15. I have only class="toplamc" which is displaying dynamic value from the summation of two textboxes. How can I sum that value from class="toplamc" instead of static value like 12. Thank you Commented Jun 28, 2020 at 8:47

1 Answer 1

1

What you could do with jQuery in this instance is to loop around your class selector, toplamc in this case, and sum up the contents.

jQuery:

var sum = 0;
$('.toplamc').each(function() {
     sum += parseFloat($(this).text());
});
$('#sum').text(sum);

This works with dynamicly added content. You only gotta make sure you run the function AFTER your dynamic content has already been created. Remember, code is executed top-down. It cannot find elements that do not exist yet.

So if you keep adding dynamic content as the sum has already been calculated, you'll need to continuously execute the sum function each time you add a new row.

Snippet example with dynamic content:

$('#createRowsBtn').on("click", function() {    
    var classCount = $('.toplamc').length;
    if(classCount > 0) {
        $('#calcTable').html("");
    }
    
    var rowCount = $('#rowCount').val();
    if(rowCount < 1 || rowCount == "") {
        alert('enter a number bigger than 0 in the input field');
    } else {
        $('#another-container').css("visibility", "visible");
        var html  = '<tr>';
            html +=     '<td>';
            html +=         'random stuff';
            html +=     '<td>';
            html +=         'more random stuff';
            html +=     '</td>';
            html +=     '<td bgcolor="#FF5733">';
            html +=         '<span class="toplamc"></span>';
            html +=         'USD';
            html +=     '</td>';

        for(var i = 0; i < rowCount; i++) {
            $('#calcTable').append(html);
        }
        
        $('.toplamc').each(function() {
            var randomNum = Math.round(Math.random() * 10);
            $(this).text(randomNum);
        });
        
        var html  = '<tr>';
            html +=     '<td>';
            html +=         'Total';
            html +=     '<td>';
            html +=         'Sum';
            html +=     '</td>';
            html +=     '<td colspan="2">';
            html +=         '<span id="sum"></span>';
            html +=         'USD';
            html +=     '</td>';
            html += '</tr>';
        $('#calcTable').append(html);
        
        
        var sum = 0;
        $('.toplamc').each(function() {
             sum += parseFloat($(this).text());
        });
        $('#sum').text(sum);
    }
});

$('#addRowBtn').on("click", function() {
    var numVal = $('#newRowVal').val();
    
    if(numVal < 1) {
        alert('please enter a value greater than 0');
        $('#newRowVal').val("");
    } else {
        $('#sum').parent().parent().remove();
        
        var html  = '<tr>';
            html +=     '<td>';
            html +=         'random stuff';
            html +=     '<td>';
            html +=         'more random stuff';
            html +=     '</td>';
            html +=     '<td bgcolor="#FF5733">';
            html +=         '<span class="toplamc">'+numVal+'</span>';
            html +=         'USD';
            html +=     '</td>';
            html += '</tr>';
            html += '<tr>';
            html +=     '<td>';
            html +=         'Total';
            html +=     '<td>';
            html +=         'Sum';
            html +=     '</td>';
            html +=     '<td colspan="2">';
            html +=         '<span id="sum"></span>';
            html +=         'USD';
            html +=     '</td>';
            html += '</tr>';
            $('#calcTable').append(html);
            
        var sum = 0;
        $('.toplamc').each(function() {
             sum += parseFloat($(this).text());
        });
        $('#sum').text(sum);
    }
});
#another-container {
    visibility: hidden;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
    <div class="form-group col-md-8">
        <div class="input-group">
            <div class="input-group-prepend">
                <span class="input-group-text rounded-0">Amount of rows:</span>
            </div>
            <input type="number" class="form-control rounded-0" id="rowCount" min="1" placeholder="number of rows" />
            <button class="btn-primary" id="createRowsBtn">Create rows</button>
        </div>
    </div>
</div>
<br />
<table class="table table-dark" id="calcTable">
</table>
<div class="row" id="another-container">
    <div class="form-group col-md-8">
        <div class="input-group">
            <div class="input-group-prepend">
                <span class="input-group-text rounded-0">Another row?:</span>
            </div>
            <input type="number" class="form-control rounded-0" id="newRowVal" min="1" placeholder="add 1 more row with a fixed value" />
            <button class="btn-primary" id="addRowBtn">Add row</button>
        </div>
    </div>
</div>

Codepen Example here.

More about the jQuery .each() function here.

Sign up to request clarification or add additional context in comments.

5 Comments

Hi Martin, I tried to use full codes which can help you to understand what I need. Try to use that codes you will understand what I need (Sub Total of tables). thank you
The approach is the same @Schadro. You have all the building blocks you need.
Yes Martin, but try the codes I pasted above. It calculate only static values in <td></td> but dynamic values will not be calculated. Please check
Because, like I said, notice how you are calculating your sum THEN adding dynamic content AFTERWARDS and NO LONGER CALCULATING THE SUM AFTER THAT? You'll need to CONTINUOUSLY calculate the sum EACH TIME you add dynamic content.
Ok let me try it. Thank you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.