I want to calculate each row's total price by multiplying individual row's inputs and then finally calculate a grand total by adding all the total values of the Total column using JQuery. I am only getting the first row to display total when I enter values. Any help will be greatly appreciated.
<script type="text/C#" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".txtMult").each(function () {
$(this).keyup(function () {
multInputs();
});
});
});
function multInputs() {
var mult = 0;
$(".txtMult").each(function () {
var $val1 = $('#val1').val();
var $val2 = $('#val2').val();
var $total = ($val1 * 1) * ($val2 * 1)
$('#multTotal').text($total);
});
}
</script>
@using (@Html.BeginForm())
{
<table>
<tr>
<th>
Quanity
</th>
<th>
Unit Price
</th>
<th>
Total
</th>
</tr>
@for (int i=0; i < 5; i++)
{
<tr>
<td>
<input class ="txtMult" name="txtEmmail" id="val1" />
</td>
<td>
<input class ="txtMult" name="txtEmmail" id="val2"/>
</td>
<td>
<span id="multTotal">0.00</span>
</td>
</tr>
}
<tr>
<td colspan="3" align="right">
Grand Total# <span id="grandTotal">0.00</span>
</td>
</tr>
</table>
}
Your html is invalid: the
id
attribute is supposed to be unique but you are repeating the same three ids in every row. The easiest way to fix this is to change your inputs to haveclass="val1"
andclass="val2"
instead ofid="val1"
and`id="val2"
, and change your row total to haveclass="multTotal"
. I'd also move thetxtMult
class to each of the tr elements with the inputs in them, for ease of selecting those rows:...and then change the selector in your jQuery code to select by class in the context of the current row. Note also that you don't need an
.each()
loop to bind the.keyup()
handlers to the elements that match your selector, just use$("someselector").keyup()
:Working demo: http://jsfiddle.net/nnnnnn/5FpWC/
Let add a class
in
to the table.At first add a change event to all inputs of the table. On change of a input field multiply all inputs of same row and update the
multTotal
andgrandTotal
check this at jsfiddle
If need to process more than 2 fields change
to