Domanda

I am trying to sum the values of a column within a table and put that sum into another html field. The challenge I'm running into is the values in the TD cells are simple text labels. http://jsfiddle.net/dm4AZ/60/

<table>
   <tr>
      <td>100</td>
   </tr>
   <tr>
      <td>200</td>
   </tr>
   <tr>
      <td>100</td>
   </tr>
</table>
<br>
<dl>
    <dt>Total Value:</dt>
    <dd id="mySum"></dd>
</dl>


$(document).ready(function(){
     colSum();
});

function colSum() {
    var sum=0;
    //iterate through each input and add to sum
    $('myTD').each(function() {     
            sum += parseInt(this.html());                     
    }); 
    //change value of total
       $('#mySum').html(sum);
}
È stato utile?

Soluzione

There is no myTD in the markup.. Also when you want to read the value of the selector in each you need to use

$(this) and not just this

 $('myTD').each(function() {     
                sum += parseInt(this.html());                     
        });

should be

$('td').each(function() {     
            sum += parseInt($(this).text());                     
    });

Check this UPDATED FIDDLE

Altri suggerimenti

This will work:

    $(document).ready(function(){
      colSum();
    });

    function colSum() {
      var sum=0;
      //iterate through each input and add to sum
      $('td').each(function() {     
        sum += parseInt($(this).text());                     
      }); 
      //change value of total
      $('#mySum').html(sum);
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top