0

Can some one help me, i need to compute 'AUTOMATICALLY' <input> that has the same class= and output into another <input id=>, this is what i've tried so far

$('.debit').change(function(e)  {
    var total = 0;
    total +=  parseFloat(this.value);
    $('#total').val(total);
});
5
  • what do you mean by auto compute? Commented May 13, 2015 at 5:54
  • Also add your html code Commented May 13, 2015 at 5:54
  • if someone input a data on <input> it will automatically output the sum to another <input> Commented May 13, 2015 at 5:55
  • <input type='text' name='debit' class='debit' id='debit"+x+"' placeholder='debit' style='width:60px'> Commented May 13, 2015 at 5:55
  • <input readonly type='text' name='total_debit_text' id='total' style='width: 60px'> Commented May 13, 2015 at 5:56

2 Answers 2

1

Try this code, get all input with .debit class name using .each like so :

$('.debit').change(function (e) {
  var total = 0;
  $('.debit').each(function(){
     var myValue = $(this).val() ? $(this).val() : 0;
     total += parseFloat(myValue);
  });      
  $('#total').val(total);
});

//or use keyup

$('.debit').keyup(function (e) {
   var total = 0;   
   $('.debit').each(function(){
     var myValue = $(this).val() ? $(this).val() : 0;
     total += parseFloat(myValue);
   });      
   $('#total').val(total);
});

DEMO

p/s : it could be better if you use .keyup instead of change.

Sign up to request clarification or add additional context in comments.

1 Comment

@Paul : Nan because there is no initial value for input. You should see the Tushar answer
0

Try this:

$('.debit').on('keyup', function (e) {
    var total = 0;
    $('.debit').each(function () {
        total += parseFloat($(this).val()) || 0;
    });

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

Demo: https://jsfiddle.net/tusharj/rvba2r2o/1/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.