Add multiple live javascript inputs

I have many input fields. when I type in one field, it is multiplied by a number. how can i make the sum of all the fields at the end?

$("#100").keyup(function(){
 $("#100_").val(this.value*100.00);
});

$("#50").keyup(function(){
    $("#50_").val(this.value*50.00);
});
$("#20").keyup(function(){
    $("#20_").val(this.value*20.00);
});
$("#10").keyup(function(){
    $("#10_").val(this.value*10.00);
});
$("#5").keyup(function(){
    $("#5_").val(this.value*5.00);
});
$("#2").keyup(function(){
    $("#2_").val(this.value*2.00);
});
$("#1").keyup(function(){
    $("#1_").val(this.value*1.00);
});

this is my code for the number multiplier. it works. but in the end I have an input field and I want to sum all input fields wit id "* _"

+4
source share
1 answer

Strategy: also use the class attribute to help you, for example, define the moneyInput class for each input (# 20_, # 50_, etc.).

Then use the following statement:

var c,sum=0;
$(".moneyInput").on("input",function(){ 
   $("#"+this.id+"_").val(this.value*parseInt(this.id));
  $(".moneyInput").each(function(){
    sum+=parseInt($(this).val());
  });
  $("#total").val(sum);
});
// the sum will store what you want, I think?

And delete all your events that were previously defined.

+2
source

All Articles