0

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>
Rajesh
  • 24,354
  • 5
  • 48
  • 79
stonypaul
  • 667
  • 1
  • 8
  • 20

2 Answers2

1

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>
Rajesh
  • 24,354
  • 5
  • 48
  • 79
1

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
}
Pete
  • 57,112
  • 28
  • 117
  • 166