Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading