I have a pivot table, for each row that is generated a <input type="number" onclick="Total();" class="input-number"/>
. What I am trying to do is that when the user increases or decreases the quantity from the input number
chosen row, the price of the "Total" column changes. The problem I have is that when I click on input number
any row, the result is "NaN" in all the Total columns.
Here the image:
Here the pivot table and jquery
<script type="text/javascript">
function Total() {
var price = $('.price').val();
var quantity = $('.input-number').val();
var result = price * quantity;
$('.total').val(result);
}
</script>
<table class="table table-striped table-primary table-bordered" id="tableComprar">
<thead>
<tr>
<th class="text-center">Imagen</th>
<th class="text-center">Nombre</th>
<th class="text-center">P/unidad</th>
<th class="text-center">Cantidad</th>
<th class="text-center">Total</th>
</tr>
</thead>
<tbody>
@foreach (Libro item in Model)
{
<tr>
<th class="text-center"><img src="/@item.UrlImagen.Replace("\\", "/")" width="80" height="100" /></th>
<th class="text-center">@item.Nombre</th>
<th class="text-center"><input type="text" class="price" value="@item.Precio" disabled /></th>
<th class="text-center">
<input type="number" onchange="Total(this);" class="input-number" value="" min="1" max="@item.Cantidad" placeholder="1"/>
</th>
<th class="text-center"><input type="text" class="total" value="@item.Precio" disabled /></th>
</tr>
}
</tbody>
</table>
Look at this code I did it with a simple function:
What happens is that you are taking all the inputs with class "price", by doing this you get an array, and multiply it with another array of "quantities", so you could generate an id for each input.
As I told you, I linked the onChange event to
input-number
, because when making changes to the quantity, they were not reflected in the total.You must include one
id
in eachinput
so that you can calculate by row; if you do it by classes - as it is currently -, changing a value in the input-number will update all the totals in the table. You can concatenate a generic name plus the index of the element inside yourfor
to fix this ;)Let us know how it goes =)
Thanks colleagues for your contribution!, Following your ideas I solved it this way:
1) Create a counter variable "idRow" that serves as the id for each row.
input
assign an id to each one concatenated with the idRow (achieving a different id for each input).2) Also, in the total() function, change to the onchange() event and pass the idRow as a parameter.
Sample of how the inputs were:
Here I pass the html code:
here jquery