Here is the code, both ASPX and the JQuery code.
The ASPX
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" class="calculate" onchange="calculate()" runat="server" Text="0"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" class="calculate" onchange="calculate()" runat="server" Text="0"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
The code is similar as previously. Only now we have addedd class=”calculate” to the TextBox in order to perform JQuery manipulation to all the textboxes with class=”calculate” (all textboxes will have class calculate, no matter of the number of textboxes inside the gridview, which will make easier to find and manipulate with them using JQuery).
The JQuery code:
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
function calculate() {
var txtTotal = 0.00;
//var passed = false;
//var id = 0;
$(".calculate").each(function (index, value) {
var val = value.value;
val = val.replace(",", ".");
txtTotal = MathRound(parseFloat(txtTotal) + parseFloat(val));
});
document.getElementById("<%=total.ClientID %>").value = txtTotal.toFixed(2);
}
function MathRound(number) {
return Math.round(number * 100) / 100;
}
</script>
<script language="javascript" type="text/javascript">
function calculate() {
var txtTotal = 0.00;
//var passed = false;
//var id = 0;
$(".calculate").each(function (index, value) {
var val = value.value;
val = val.replace(",", ".");
txtTotal = MathRound(parseFloat(txtTotal) + parseFloat(val));
});
document.getElementById("<%=total.ClientID %>").value = txtTotal.toFixed(2);
}
function MathRound(number) {
return Math.round(number * 100) / 100;
}
</script>
Using this JQuery each function, we can easily iterate trough all html objects containing the class name calculate, which in our case are the text boxes.
That’s it.
No comments:
Post a Comment