I have this code, but I want to add it in case if the value in the price field is equal to a string, how can this value be discarded and not counted and sum the rest of the values of type number
var theSummry = 0;
$(".price").each(function() {
theSummry = parseInt($(this).text());
})
$(".the-total").text(theSummry);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table style="width:70%;text-align: center;margin: 30px auto;">
<tr>
<th>Person 1</th>
<th>Person 2</th>
<th>Person 3</th>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td class="price">10</td>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td class="price">qwe</td>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td class="price">10</td>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td class="price">30</td>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td class="price">10</td>
</tr>
<tr class="the-total"></tr>
</table>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
To achieve this you can coalesce the NaN
output from trying to parseInt()
a string to a 0
value using the logical OR operator:
var theSummry = 0;
$(".price").each(function() {
theSummry = parseInt($(this).text(), 10) || 0;
})
$(".the-total").text(theSummry);
table {
width: 70%;
text-align: center;
margin: 10px auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table>
<tr>
<th>Person 1</th>
<th>Person 2</th>
<th>Person 3</th>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td class="price">10</td>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td class="price">qwe</td>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td class="price">10</td>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td class="price">30</td>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td class="price">10</td>
</tr>
<tr class="the-total"></tr>
</table>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>