While trying to get the sum total of the values of an html table column, my variable is returning concatenated strings: instead of 1 + 2 + 3 = 6
, I am seeing 1 + 2 + 3 = 123
.
The "votes" column values are incremented by an ajax call when the users click on the colors, which is correct. But I also hope to see the sum of all values when "total" is clicked.
Jquery:
$('#total').on('click', function() {
var sumofval = 0;
$(".val").each(function () {
sumofval = sumofval + ($(this).html());
$('#totalr').html(sumofval);
console.log(sumofval);
});
});
The HTML Color-Votes Table:
<table id="tcol" style="width:60%;">
<thead>
<tr>
<th>Color</th>
<th>Votes</th>
</tr>
</thead>
<tr>
<td id="red"><a href="#">Red</a></td>
<td id="redr" class="val"></td>
</tr>
<tr>
<td id="orange"><a href="#">Orange</a></td>
<td id="oranger" class="val"></td>
</tr>
<tr>
<td id="yellow"><a href="#">Yellow</a></td>
<td id="yellowr" class="val"></td>
</tr>
<tr>
<td id="green"><a href="#">Green</a></td>
<td id="greenr" class="val"></td>
</tr>
<tr>
<td id="blue"><a href="#">Blue</a></td>
<td id="bluer" class="val"></td>
</tr>
<tr>
<td id="indigo"><a href="#">Indigo</a></td>
<td id="indigor" class="val"></td>
</tr>
<tr>
<td id="total"><a href="#">TOTAL</a></td>
<td id="totalr"></td>
</tr>
</table>