htmljqueryadditionsubtotal

How can I add numbers of table row in a table using jquery?


I'm able to add numbers from input to the table on click of a button. But I can't get the total of all the numbers in the table on click of the button.

How can I add the numbers of the table row on click of a button?

<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
 $("button#add").click(function(){
  $("table#content-table").append('<tr><td class="table-letter">' + $("input#letter").val() + '</td><td class="table-number">' + $("input#number").val());

  $("td.table-total").text( parseInt($("td.table-number").html()) += parseInt($("td.table-number").html()) )
 });
});
</script>
</head>
<body>

<table id="content-table">
 <tr>
  <th>Letter</th>
  <th>Number</th>
 </tr>
 <tr>
  <td class="table-letter">A</td>
  <td class="table-number">5</td>
 </tr>
</table>
<table>
 <tr>
  <td>Total</td>
  <td class="table-total"></td>
 <tr>
</table>

<form action="javascript:void(0);">
 <input id="letter" name="letter" placeholder="Enter letter" required />
 <input type="number" id="number" name="number" placeholder="Enter number" required />
 <button id="add">ADD</button>
</form>

</body></html>

Solution

  • Here is the solution, I have written code in old Javascript I think if you are using jQuery maybe you are running your code in old browsers

    I have also added missing close tags

    $(document).ready(function() {
     $("button#add").click(function() {
      $("table#content-table").append('<tr><td class="table-letter">' + $("input#letter").val() + '</td><td class="table-number">' + $("input#number").val() + '</td></tr>');
    
        var total = 0;
        var numbers = $(".table-number");
        var numbersLength = numbers.length;
      
        for (var x = 0; x < numbersLength; x++) {
            total += parseInt($(numbers[x]).html());
        }
    
      $("td.table-total").text(total);
     });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table id="content-table">
     <tr>
      <th>Letter</th>
      <th>Number</th>
     </tr>
     <tr>
      <td class="table-letter">A</td>
      <td class="table-number">5</td>
     </tr>
    </table>
    <table>
     <tr>
      <td>Total</td>
      <td class="table-total"></td>
     <tr>
    </table>
    
    <form action="javascript:void(0);">
     <input id="letter" name="letter" placeholder="Enter letter" required />
     <input type="number" id="number" name="number" placeholder="Enter number" required />
     <button id="add">ADD</button>
    </form>