Why won't my inputs value sum?

Im trying to do a sum of values i get from id but it keeps appending second value to first instead of doing sum as it should.

Example 23+25=2325

Heres my code:

This is the code im using to sum.

        $('input').blur(function() {
            for (var i=1; i<=value; i++) {

              var one = document.getElementById("veb_blocos-"+i).value; 
              var two = document.getElementById("veb_pellet-"+i).value;
              var sum1 = one+two;
              document.getElementById("total1-"+i).value = sum1; 
           };

        });

Answers:

Answer

Because the value of an input is a string. Cast it to int.

$('input').blur(function() {
    for (var i=1; i<=value; i++) {

      var one = document.getElementById("veb_blocos-"+i).value; 
      var two = document.getElementById("veb_pellet-"+i).value;
      var sum1 = parseInt(one,10)+parseInt(two,10);
      document.getElementById("total1-"+i).value = sum1; 
   };

});
Answer

Try this:

var one = parseInt(document.getElementById("veb_blocos-"+i).value, 10); 
var two = parseInt(document.getElementById("veb_pellet-"+i).value, 10);
Answer

Here is the safest possible solution (presuming the requested DOM nodes are present):

$('input').blur(function () {
    var i = 0,
        one = 0,
        two = 0;
    for (i = 1; i <= value; i += 1) {
        one = Number(document.getElementById("veb_blocos-" + i).value);
        two = Number(document.getElementById("veb_pellet-" + i).value);
        if (isNaN(one)) {
            one = 0;
        }
        if (isNaN(two)) {
            two = 0;
        }
        document.getElementById("total1-" + i).value = one + two;
    };
});
Answer

Try:

$('input').blur(function() {
            for (var i=1; i<=value; i++) {

              var one = parseInt(document.getElementById("veb_blocos-"+i).value); 
              var two = parseInt(document.getElementById("veb_pellet-"+i).value);
              var sum1 = one+two;
              document.getElementById("total1-"+i).value = sum1; 
           };

        });
Answer

It's because your values are string datatypes instead of a number type. You'll need to parse them first.

$('input').blur(function() {
            for (var i=1; i<=value; i++) {

              var one = parseFloat(document.getElementById("veb_blocos-"+i).value); 
              var two = parseFloat(document.getElementById("veb_pellet-"+i).value);
              var sum1 = one+two;
              document.getElementById("total1-"+i).value = sum1; 
           };

        });

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.