JQuery: how to subtract the numeric values ​​of each text input field in an array from an array of the corresponding array?

I have two sets of input fields like this that differ in 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>

Checks are needed to ensure that only integer values ​​can be entered in these fields.

How to subtract the value of each input field in .columntwofrom the value in the corresponding field in .columnoneon change()in this text box .columntwo? Zero values ​​should be considered zero.

For example, in change()the first input field in, columntwosubtract the value of the first input field in .columntwofrom the first field in .columntwo. Other fields remain unchanged.

Thanks in advance!

+3
source share
2 answers

, . , (columntwo 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);
});

: http://jsfiddle.net/fJLAw/

+2

, columnone columntwo,

$('input.columntwo').change(function() {
    var $this = $(this);
    $this.val(parseInt($('input.columnone').eq($this.index()).val(),10) - parseInt($this.val(),10));
});
+3

All Articles