开发者

Subtracting values from multiple input fields

I'm using the following code to take the value of one field, subtract it from the value of another field and display the result.

$(document).ready(function() {  

    var numIn;
    var numOut;
    var total;

    $('#submit').click(function() {
        numIn = $('input.in').val();
        numOut = $('input.out').val();
        total = numIn-numOut;

        $('span').remove();
        $('body').append('<span>&#163;'+total+'</span>');
        $('span').fadeIn(250);
    });
});

I want to create a sort of income/expenditure calculator. so my question is, say I had multiple income fields and multiple expenditure fields how would I ta开发者_C百科ke the total value from the income fields away from the total value of the expenditure fields.

Here is an example form in case I haven't been clear.

<form>
<input class="in" type="text">
<input class="in" type="text">
<input class="in" type="text">
<input class="in" type="text">
<input class="out" type="text">
<input class="out" type="text">
<input class="out" type="text">
<input class="out" type="text">
<input type="submit" id="submit" value="Submit">


You could loop over the .in and .out fields, and add their values as you go.

Example: http://jsfiddle.net/tXPeg/3/

var numIn = 0;
var numOut = 0;
var total;

$('#submit').click(function() {
    $('input.in').each(function() {
        return numIn += (parseFloat(this.value) || 0);
    });
    $('input.out').map(function() {
        return numOut += (parseFloat(this.value) || 0);
    });
    total = numIn - numOut;

    $('span').remove();
    $('body').append('<span>&#163;' + total + '</span>');
    $('span').fadeIn(250);
    return false;
});​

EDIT: Changed to use parseFloat() instead of parseInt().


Actually after testing a little further the only problem is that if one or more fields are empy it returns 'NaN'.

I tried adding conditional statements to check that the field had a value but no luck: Feel free to edit my example: http://jsfiddle.net/QaEcD/3/

$('#submit').click(function() {
    var numIn = 0;
    var numOut = 0;
    var total = 0;

    $('input.in').each(function() {
        if($(this).val().length !== 0){
            return numIn = numIn + parseInt(this.value);
        });
    });
    $('input.out').map(function() {
        if($(this).val().length !== 0){
            return numOut = numOut + parseInt(this.value);
        });
    });

    total = numIn-numOut;

    $('span').remove();
    $('body').append('<span>&#163;'+total+'</span>');
    $('span').fadeIn(250);
    return false;
});

});

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜