开发者

How to update total sum from multiple optional inputs?

开发者 https://www.devze.com 2023-03-07 02:15 出处:网络
I have a somewhat large form that takes monetary values and has a total sum at the end. I am trying to automatically update the total using javascript (jQuery). Some of the input fields are optional.

I have a somewhat large form that takes monetary values and has a total sum at the end. I am trying to automatically update the total using javascript (jQuery). Some of the input fields are optional. I am looking at using the .change() method. Is there a better way than to associate a change method with every single input field?

The script just needs to take the values from the input fields (if any), add them up and display the total somewhere. My idea was to tag each of the relevant input fields and select them. Is this possible?

[edit] example code:

<input name="input1" type"text" />
<input name="input2" type"text" />
<input name="input3" type"text" />
<input name="input4" type"text" />
<input name="input5" type"text" />
<input name="input6" type"text" />

<input name="total" type="text" />

All the inputs are initially blank. I want the total to update as I enter values into the inputs.开发者_开发问答


If you add a class (call it "foo") to each input element that you want to total up, then this will work:

var $form = $('#my-form-id'),
    $summands = $form.find('.foo'),
    $sumDisplay = $('some-other-selector');

$form.delegate('.foo', 'change', function ()
{
    var sum = 0;
    $summands.each(function ()
    {
        var value = Number($(this).val());
        if (!isNaN(value)) sum += value;
    });

    $sumDisplay.text(sum);
});

Demo: http://jsfiddle.net/mattball/XcYTc/


I think that would work. Attach a change event to the class. I think the easiest thing to do would be to loop over the collection in the change callback and sum up all the values. You could probably just use the value of the currently changed item if you wanted, but for some reason I feel it might be safer to recalculate.

$(".money").change(function(){
     var total = 0;
     $(".money").each(function(){
         total += $(this).val();
     }
     //now you can use total
});
0

精彩评论

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