3

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!

1
  • Don't you want to add the classes columnone and columntwo to the wrapping div,s instead of to each input element? Commented May 24, 2011 at 7:14

2 Answers 2

3

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));
});
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for simple and fast solution . use parseFloat instead 'parseInt`
Thanks. This doesn't seem to be working when I prefix line 3 with 'var difference =' and then 'alert(difference);'
2

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/

3 Comments

@diEcho Yup, but I used parseInt because the OP mentioned integers.
When I use this, all .columntwo values are always being subtracted from the first input field of .columnone.
@Stroller do you mean in the fiddle or in your code? The fiddle works fine for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.