-1

I am trying to add the multiplication result, but the result I want doesn't match, can you help me to see where the error is in my javascript code?

The results I want: ((x*10)/100)+x = ... or ((30.000 * 10) / 100)+30.000 = 33000

but why the results i got = 300030000

var x = document.getElementById("x");
var y = document.getElementById("y");
var d = document.getElementById("d");
var xstored = x.getAttribute("data-in");
var ystored = y.getAttribute("data-in");
setInterval(function(){
    if( x == document.activeElement ){
     var temp = x.value;
     if( xstored != temp ){
       xstored = temp;
       x.setAttribute("data-in",temp);
       calculate();
     }
    }
    if( y == document.activeElement ){
     var temp = y.value;
     if( ystored != temp ){
       ystored = temp;
       y.setAttribute("data-in",temp);
       calculate();
     }
    }
},50);

function calculate(){
 d.innerHTML = ((x.value * y.value) / 100) + x.value ;
}
x.onblur = calculate;
calculate();
<div class="section">
    <div class="container">
        <h3>Calculate</h3>
        <input id="x" data-in="" type="text" />
        x <input id="y" data-in="" type="text" />
        <hr>
        <div id="d"></div>
    </div>
</div>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Does `var temp = parseInt(x.value);` solve it? You issue seems to be that two strings are being concatenated – Nick Dec 30 '20 at 01:02
  • Cast your input values to integers - they're interpreted as strings by default, thus the `+` operator concatenates them. – esqew Dec 30 '20 at 01:04

1 Answers1

0

The value of an input element is a string, so you need to convert it to a number before adding to prevent it from being treated as string concatenation. This can be done using the unary plus operator.

d.innerHTML = ((x.value * y.value) / 100) + (+x.value);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80