Javascript – 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();      
    console.log("value after each: " + value);


<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" />

Best Solution

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;