Cristian Meneses Cristian Meneses - 6 months ago 10
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

<table>
<thead>
<tr>
<td>Qty</td>
<td>Description</td>
<td>Unit Price</td>
<td>Total Price</td>
<tr>
</thead>
<tbody>
<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>
<tr>
</tbody>
</table>

<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
quantity
*
unitPrice
) and assign it to
totalPrice
. And assign the sum of
totalPrice
to
total
.

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;

$total.val(0);

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!

Answer

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]);
singleElementCantidades.val();

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.

Comments