Stroller
Stroller

Reputation: 33

jQuery: How to subtract numeric values of each text input field in an array from that of a corresponding array?

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

Answers (2)

Freek
Freek

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

JohnP
JohnP

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

Related Questions