一旦它们都具有值,就动态地对标签的值求和

时间:2016-02-01 11:59:20

标签: javascript jquery asp.net aspx-user-control

我有一系列asp Radiobuttons正在填充标签的值,但是现在使用jQuery检查,如果所有标签都有值,那么我想动态地对值进行求和。 什么代码/函数可以使用clsTxtToCalculate类或引用标签值来实现这一点?

<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 个答案:

答案 0 :(得分:1)

您可以循环标签并总结值:

&#13;
&#13;
function notify() {
  var labels = $(".clsTxtToCalculate");
  var total = 0; 
  $.each(labels, function(index,lbl){
    total += parseInt($(lbl).text());
  });
  alert(total)
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

在你的收音机更换活动中(我猜你有其中一个填充标签),你可以在填充标签文字后做同样的事情:

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

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