Search code examples
javascriptjqueryasp.netaspx-user-control

Dynamically sum the values of labels once they all have values


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>

Solution

  • 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
    }