Reputation: 25745
i have this dynamically populated form fields.
<input type="text" name="quantity[]" placeholder="quantity"/>
<input type="text" name="quantity[]" placeholder="quantity"/>
<input type="text" name="quantity[]" placeholder="quantity"/>
<input type="text" name="quantity[]" placeholder="quantity"/>
<input type="text" name="quantity[]" placeholder="quantity"/>
on jQuery's keyup i want to fetch all the value from input[name="quantity[]"]
and perform some calculations like total quantity i.e something like
(field1 quantity value) + (field2 quantity value) + (field3 quantity value) ... n
i tried fetching the value like this.
$('input[name="quantity[]"]').keyup(function(){
var val = $(this).val();
});
this only fetches the value of first element and ignores the rest of fields. how do i go with what i want?
thank you
Upvotes: 1
Views: 2271
Reputation: 87073
var ref = $('input[name^="quantity"]');
ref.keyup(function(e){
var result = 0;
ref.each(function() {
console.log($(this).val());
if($(this).val().length && $(this).val() != '') {
result += parseInt($(this).val());
}
console.log(result);
});
});
Upvotes: 1
Reputation: 134
try this:
<input type="text" name="quantity[]" placeholder="quantity"/>
<input type="text" name="quantity[]" placeholder="quantity"/>
<input type="text" name="quantity[]" placeholder="quantity"/>
<input type="text" name="quantity[]" placeholder="quantity"/>
<input type="text" name="quantity[]" placeholder="quantity"/>
<input type="text" name="res" placeholder="Resultado"/>
$(document).ready(function() {
$('input[name="quantity[]"]').keyup(function(){
var val = 0;
$('input[name="quantity[]"]').each(function() {
val += Number($(this).val());
});
$('input[name="res"]').val(val);
});
});
fuente con jsfiddle
by JNE
Upvotes: 2
Reputation: 19882
A simple solution is to assign each text box a class let suppose quantity then
var total_quantity = 0;
$('.quantity').keyup(function()
{
$(this).each(function()
{
total_quantity += $(this).val();
});
});
Upvotes: 0
Reputation: 9538
var $quantity = $('input[name="quantity[]"]');
$quantity.keyup(function(){
var val = 0;
$quantity.each(function(){
val += parseInt($(this).val(), 10);
});
});
Upvotes: 2