Reputation: 33
I have two sets of of input fields like this, differentiated by their classes:
<div>
<input type="text" class="columnone" />
<input type="text" class="columnone" />
<input type="text" class="columnone" />
</div>
<div>
<input type="text" class="columntwo" />
<input type="text" class="columntwo" />
<input type="text" class="columntwo" />
</div>
Necessary validations are in place to ensure that only integer values can be input by the user into these fields.
How do I subtract the value of each input field in .columntwo
from the value in the corresponding field in .columnone
on change()
in that particular .columntwo
text field? Null values should be considered zero.
For example, on change()
in the first input field in columntwo
, subtract the value of the first input field in .columntwo
from the first field in .columntwo
. Other fields remain unchanged.
Thanks in advance!
Upvotes: 3
Views: 5797
Reputation: 1546
Under the assumption that you don't have any other elements with class columnone or columntwo, you can do
$('input.columntwo').change(function() {
var $this = $(this);
$this.val(parseInt($('input.columnone').eq($this.index()).val(),10) - parseInt($this.val(),10));
});
Upvotes: 3
Reputation: 50039
This is a bit convoluted, but it will work. This works on the assumption that you want to trigger the function both ways (columntwo and columnone)
$('.columnone, .columntwo').change(function() {
var $this = $(this);
var sum = 0;
var index = $this.index();
if ($this.hasClass('columnone')) {
var val1 = parseInt($this.val(), 10);
var val2 = parseInt($('.columntwo:eq(' + index + ')').val(), 10);
} else {
var val2 = parseInt($this.val(), 10);
var val1 = parseInt($('.columnone:eq(' + index + ')').val(), 10);
}
val1 = (isNaN(val1)) ? 0 : val1;
val2 = (isNaN(val2)) ? 0 : val2;
sum = val2 - val1;
//console.log(sum);
alert(sum);
});
Here's the fiddle : http://jsfiddle.net/fJLAw/
Upvotes: 2