Dynamically sum the values of labels once they all have values

1.2k Views Asked by At

I have a series of asp Radiobuttons which are populating the values of labels fine, but now using a jQuery check, if all of the labels have values then I want to dynamically sum the values. What code/function would achieve this, using the clsTxtToCalculate class or referencing the label values?

<tr>
  <td>
    <asp:Label ID="lblScore1" CssClass="center clsTxtToCalculate" clientidmode="Static" runat="server" AutoCompleteType="None" />
  </td>
  <td>
    <asp:Label ID="lblScore2" CssClass="center clsTxtToCalculate" clientidmode="Static" runat="server" AutoCompleteType="None" />
  </td>
  <td>
    <asp:Label ID="lblScore3" CssClass="center clsTxtToCalculate" clientidmode="Static" runat="server" AutoCompleteType="None" />
  </td>
  <td>
    <asp:Label ID="lblScore4" CssClass="center clsTxtToCalculate" clientidmode="Static" runat="server" AutoCompleteType="None" />
  </td>
</tr>
2

There are 2 best solutions below

0
On BEST ANSWER

In your radio change event (I'm guessing you have one of these to populate the labels), you could do something like this after you have populated the label text:

var labels = $('.clsTxtToCalculate'),
    labelsWithText = labels.filter(function() {
      return $(this).text() != '';
    });

if (labels.length == labelsWithText.length) {
  // do calculation here
}
2
On

You can loop over labels and sum up values:

function notify() {
  var labels = $(".clsTxtToCalculate");
  var total = 0; 
  $.each(labels, function(index,lbl){
    total += parseInt($(lbl).text());
  });
  alert(total)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <Label ID="lblScore1" class="center clsTxtToCalculate">10</label>
    </td>
    <td>
      <Label ID="lblScore2" class="center clsTxtToCalculate">20</label>
    </td>
    <td>
      <Label ID="lblScore3" class="center clsTxtToCalculate">30</label>
    </td>
    <td>
      <Label ID="lblScore4" class="center clsTxtToCalculate">40</label>
    </td>
  </tr>
</table>
<button onclick="notify()">Calculate</button>