Can I get the SUM of td value and input value inside another td with JS?

Advertisements

I have a table which is contains a td values and input inside another td which is contains a value too.

I want to get the sum of the td value and the other td that contain the input.

This is the code but it doesn’t work perfectly:

let gross = 0;
$(".total").each(function() {
  gross += parseFloat($(this).val());
});
document.getElementById('gross_amount').innerHTML = gross;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <td>#</td>
      <td>Name</td>
      <td>Age</td>
      <td>Salary</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Hazem</td>
      <td>20</td>
      <td class="total">50.00</td>
    </tr>
    <tr>
      <td>2</td>
      <td>John</td>
      <td>25</td>
      <td><input class="total" type="text" value="60.00" /></td>
    </tr>
  </tbody>
  <div id="gross_amount"></div>
</table>

>Solution :

The issue is because one element is a td and the other is an input, and only input elements have a value property to be read by val().

To fix the issue you can detect the type of element using tagName and then retrieve either the text() or val() based on that:

let gross = 0;
$(".total").each(function() {
  let $el = $(this);
  gross += parseFloat(this.tagName == 'INPUT' ? $el.val() : $el.text());
});
$('#gross_amount').text(gross.toFixed(2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <td>#</td>
      <td>Name</td>
      <td>Age</td>
      <td>Salary</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Hazem</td>
      <td>20</td>
      <td class="total">50.00</td>
    </tr>
    <tr>
      <td>2</td>
      <td>John</td>
      <td>25</td>
      <td><input class="total" type="text" value="60.00" /></td>
    </tr>
  </tbody>
</table>
<div id="gross_amount"></div>

Note that the #gross_amount div needs to be outside the <table> element for your HTML to be valid. Also, if you’ve loaded jQuery then you might as well keep the code consistent and use it to update the #gross_amount element too.

Leave a ReplyCancel reply