开发者

Get total of all input values with jQuery

I need the total of all the values from my input. The result must be displayed in the input field total that is readonly.

The user can enter 1 or more values. The problem is that my var value is not correct. I'd also like to know how I can return the value immediately by onchange?

$(document).ready(function() {
  $("div#example input").change(function() {
    var value = '';    
    $("div#example input[name!=total]").each(function() {
      value += $(this).val();      
    });
    c开发者_开发问答onsole.log("value after each: " + value);
  });
})

HTML:

<div id="example">
   <input type="text" size="5" id="value1" name="value1" />
   <input type="text" size="5" id="value2" name="value2" />
   <input type="text" size="5" id="value3" name="value3" />
   <input type="text" size="5" id="value4" name="value4" />
   <input type="text" size="5" id="value5" name="value5" />
   <input type="text" size="5" id="total" readonly="readonly" class="bckground" name="total" />


Try something like this:

$(document).ready(function() {
    $("div#example id^='value'").change(function() {
        var value = 0;

        $("div#example input[name!=total]").each(function() {
            var i = parseInt($(this).val());

            if (!isNaN(i))
            {
                value += i;
            }
        });

        $('#total').val(value);
    });
})


use += parseInt($(this).val());


var sum = 0;  
$('input[id^=value]').each (function(){ sum+=$(this).val(); });
$('#total').val( sum );

:]


I think this might be closer:

<script type="text/javascript">

$(document).ready(function() {

  $("#example value").change(function() {
    var total = 0;    
    $("#example value").each(function() {
      total += parseInt($(this).val());      
    });
    window.console && console.log("value after each: " + total);
  });
})

</script> 

<div id="example">
   <input type="text" size="5" class="value" name="value1" />
   <input type="text" size="5" class="value" name="value2" />
   <input type="text" size="5" class="value" name="value3" />
   <input type="text" size="5" class="value" name="value4" />
   <input type="text" size="5" class="value" name="value5" />
   <input type="text" size="5" id="total" readonly="readonly" class="bckground" name="total" />
</div>

Your original selector for $.change() was including the total box, which I suspect you don't want.

Am I correct in guessing you want to add numbers? Your original 'value' variable was a string.

And BTW, it's safer to use the 'window.console && console.log' idiom, since there won't be a console variable for many users. (Though I bet that line was only there for debugging.)

EDIT

Added parseInt() based on other suggestions.


Use the jQuery form serialization:

alert($("form_id").serialize());

There is also a comparison for different serialization types: http://jquery.malsup.com/form/comp/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜