Reputation: 9074
I have dynamically generated text boxes and want to do calculations with their values using jquery.
The text box names are as follows :
A[1] , B[1] - on change event , Alert SUM of values of A[1] and B[1]
A[2] , B[2] - on change event , Alert SUM of values of A[2] and B[2]
A[3] , B[3] - on change event , Alert SUM of values of A[3] and B[3]
.
.
.
.
A[10] , B[10] - on change event , Alert SUM of values of A[10] and B[10]
How to make a function in jquery for this task. Please help me in accomplishing this task.
I have this code but its for all the text boxes A and B , but I want to specify SETS OF VALUES LIKE SUM of A[1] and B[1] , SUM of A[2] and B[2] .......
$("input[type='text'][name^='A'] ,input[type='text'][name^='B']").
keyup(function(){
alert(sumThemUp());
});
function sumThemUp(){
var sum = 0;
$("input[type='text'][name^='A'] ,input[type='text'][name^='B']").
each(function(){
sum+= parseInt($(this).val());
});
return sum;
};
My HTML is:
<input type="text" name="A[1]">
<input type="text" name="B[1]">
<input type="text" name="A[2]">
<input type="text" name="B[2]">
.
.
.
.
.<input type="text" name="A[10]">
<input type="text" name="B[10]">
Upvotes: 2
Views: 2975
Reputation: 1326
This is probably the simplest way to do it that I can think of. It will require a slight modification to your dynamic DOM stuff, but I assume you always generate an A and a B, so this shouldn't be a problem.
HTML:
<span class="calc_group">
<input type="text" name="A[1]">
<input type="text" name="B[1]">
</span>
<span class="calc_group">
<input type="text" name="A[2]">
<input type="text" name="B[2]">
</span>
jQuery:
NOTE: this will NEED to be called within your dynamic DOM function on every addition!
function doAttachment(){
$('.calc_group input').unbind('keyup');
$('.calc_group input').keyup(function(){
var sum = 0;
$(this).parent().children().each(function(){
sum += parseInt($(this).val());
});
alert(sum);
});
}
Upvotes: 1
Reputation: 87073
I think you're trying something like this:
$('input[type=text]').on('keyup', function() {
var cur = this.name;
if(cur.indexOf('A') == 0){
var target = 'B' + cur.replace('A','');
} else target = 'A' + cur.replace('B','');
var targetVal = $('input[name="'+ target +'"]').val();
var sum = parseInt(this.value) + parseInt(targetVal ? targetVal: 0);
console.log(sum);
});
Upvotes: 1