Reputation: 378
I'm trying to multiply values of inputs using JQuery.
<tr>
<td><input type="text" name="qtd[1]" size="2" /></td>
<td><input type="text" name="price[1]" size="10" /></td>
<td><input type="text" name="total[1]" size="10" /></td>
</tr>
<tr>
<td><input type="text" name="qtd[2]" size="2" /></td>
<td><input type="text" name="price[2]" size="10" /></td>
<td><input type="text" name="total[2]" size="10" /></td>
</tr>
<input type="hidden" value="2" name="qtd_itens" />
Basically i'm trying to show the total[i] as soon as the user fills qtd[i] and price[i]..
$(':input').bind('keypress keydown keyup change',function(){
for ($i = 0; $i < $(':input[name="qtd_itens"]').val(); $i++)
var acho = parseFloat($(':input[name="qtd[' + $i + ' ]"]').val(),10),
alto = parseFloat($(':input[name="price[' + $i + ']"]').val(),10);
var v = '';
if (!isNaN(acho) && !isNaN(alto)){
v = (acho * alto);
}
$(':input[name="total[' + $i + ']"]').val(v.toString());
}
});
Any help?
code: http://jsfiddle.net/gilbertogm85/XSAk5/1/
Upvotes: 0
Views: 307
Reputation: 146191
You may try something like this:
$(function(){
$('input[name^="price"]').on('keyup change',function(){
var prc = $(this),
qty = prc.closest('tr').find('input[name^="qtd"]'),
tot = prc.closest('tr').find('input[name^="total"]');
if(check(prc.val()) && check(qty.val())) {
var p = parseFloat((prc.val()).replace(',','')),
q = parseFloat((qty.val()).replace(',', '')),
total = p * q;
$(tot.val(total.toFixed(2)));
}
});
function check($val) { return $val.match("^[0-9,\.]+$"); }
});
Upvotes: 1
Reputation: 144659
There is a syntax error in your code, missing {
for the for
statement. Also note that parseFloat
function only accepts 1 argument, it seems you want to use the parseInt
function which accepts radix as the second argument.
Instead of using the for
loop which is not necessary you can select the closest tr
and then set the value:
$('input').on('keyup change', function (e) {
var $i = $(this).closest('tr').find('input'),
acho = parseFloat($i.eq(0).val()),
alto = parseFloat($i.eq(1).val()),
val = (acho * alto);
if ( !isNaN(val) ) {
$i.eq(2).val(val);
}
});
Upvotes: 0