Zulu Khan
Zulu Khan

Reputation: 45

Prevent adding of textbox values after they have been added

I have a few textboxes which are supposed to have numeric values. On blur event of each textbox the value of that particular textbox is added and displayed in another textbox. So like if someone enters 10 in the first textbox, the last textbox should display 10, and if 20 is entered in the next textbox, the value should add and display 30 in the last textbox.

<input type="text" class="sum" /> 
<input type="text" class="sum" />
<input type="text" class="sum" />
<input type="text" class="sum" />
<input type="text" class="sum" />

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

Using jquery i do the following,

$('.sum').blur(function(){
 $('#total').val(parseFloat($(this).val())+parseFloat($('#total').val()));
});

As can be seen there is a problem, if any textbox is focussed once again, for any reason, the same value again to the Grand Total. How can i ensure that a value from a textbox once Added to the total doesn't get added again.

Upvotes: 1

Views: 65

Answers (2)

Dan Philip Bejoy
Dan Philip Bejoy

Reputation: 4391

You can find a new sum each time blur event fires,

$('.sum').blur(function() {
  var sum = 0;
  $('.sum').each(function(){
     var val = $(this).val();
    if(!isNaN(val) && val != "") {
      sum+=parseFloat(val); 
    }
  });
  $('#total').val(sum);
});

The number check is present since your input type is not numeric and can accept any alpha numeric strings and special characters.

$('.sum').blur(function() {
  var sum = 0;
  $('.sum').each(function() {
    var val = $(this).val();
    if (!isNaN(val) && val != "") {
      sum += parseFloat(val);
    }
  });
  $('#total').val(sum);
});
<input type="text" class="sum" />
<input type="text" class="sum" />
<input type="text" class="sum" />
<input type="text" class="sum" />
<input type="text" class="sum" />

<input type="text" id="total" value="0" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Dekel
Dekel

Reputation: 62576

Instead of adding the new one every time, just sum all of them every time each of them changed:

$('.sum').blur(function() {
  var new_sum = 0;
  $('.sum').each(function(i, el) {
    if ($(el).val()) {
      new_sum += parseFloat($(el).val());
    }
  });
  $('#total').val(new_sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="sum" /> 
<input type="text" class="sum" />
<input type="text" class="sum" />
<input type="text" class="sum" />
<input type="text" class="sum" />

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

Upvotes: 0

Related Questions