Cristian Meneses Cristian Meneses - 10 months ago 40
jQuery Question

Jquery : Product between 2 lists of inputs into a 3rd list

I don't have much experience in jQuery, I'm facing the following challenge

I have the following table

<td>Unit Price</td>
<td>Total Price</td>
<tr id="itemRow">
<td><input type="text" name="quantity"/></td>
<td><input type="text" name="description"/></td>
<td><input type="text" name="unitPrice"/>/td>
<td><input type="text" name="totalPrice"/></td>

<input type="text" name="total"/>

Additionally, I'm able to clone #itemRow as many times as required, enlarging the amount of items.

The idea is to calculate the total price for each row (by
) and assign it to
. And assign the sum of

This is the javascript I'm using, but I get an error that says "cantidades[i].val() is not a function"

function calculate(){

var $total = $('#total');

var $cantidades = $('input[name=quantity]')
var $unitarios = $('input[name=unitPrice]')
var $totales = $('input[name=totalPrice]')

var len = $cantidades.length;


for (var i = 0; i < len; i++){
// calculate total for the row. ERROR HERE!
$totales[i].val($cantidades[i].val() * $unitarios[i].val());

// Accumulate total
$total.val($totalExento.val() + $totales[i].val());

What am I missing? I think I'm not getting "jQuery objects" from the selector but I'm not sure hot to do this.

Thanks in advance!


This line: var $cantidades = $('input[name=quantity]') retrieves a jQuery instance that cannot be accessed like you did with $cantidades[i].

Fix it like this:

var singleElementCantidades = $($cantidades[i]);

What happened is that $('input[name=quantity]') retrieves an array that is an instance of jQuery. And when you access its content by using cantidades[i] you are not managing a jQuery instance anymore, you are accessing something else wich doesn't have the definition of val.