-2
<!DOCTYPE html>
<html>
<head>
    <title>Function</title>

    <script type="text/javascript">
        function sum(x,y) {
            var z = x+y;
            document.write("Sum is"+z);
        }
    </script>
</head>
<body>
    <form>
        <input type="" id="t1" name=""/>
        <input type="" id="t2" name=""/>
        <input type="button" onclick="sum(t1.value,t2.value)" value="Click me"/>
    </form>
</body>
</html>

Hi Guys, I am a beginner with JavaScript and I'm facing this little problem. If I enter 5 and 5 the result is 55. But I want to sum up these values.

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84

2 Answers2

0

As @TonyDong said, uses parseInt to convert the string to int if desired input is integer.

To make your function works better, you need to validate the inputs first before sum.

Below is one example:

  1. make the type of two inputs are 'number'

  2. checkValidity() for the form or two inputs in function=sum. if validated, sum the values, if not, return error.

<!DOCTYPE html>
<html>
<head>
    <title>Function</title>

    <script type="text/javascript">

        function sum(x,y)
        {
            if(document.getElementById("submit").checkValidity()) {
              var z = parseInt(x)+parseInt(y);
              document.write("Sum is "+z);
            }
            else {
              document.write("Input value must be Int!");
            }
        }
    </script>
</head>
<body>

    <form id="submit">
        <input id="t1" name="" type="number"/>
        <input id="t2" name="" type="number"/>
        <input type="button" onclick="sum(t1.value,t2.value)" value="Click me"/>
    </form>

</body>
</html>
Sphinx
  • 10,519
  • 2
  • 27
  • 45
  • May I know why down vote? If anything is wrong, let me know. I will update or delete the answer. Thanks. – Sphinx Mar 06 '18 at 20:12
-1

You should covert x and y to integers first, like parseInt(x) and parseInt(y) while doing the summation. Then, instead of document.write, you can use console.log.

<!DOCTYPE html> 
<html>
 <head>
 <title>Function</title>
 <script type="text/javascript"> 
function sum(x,y) { 
var z = parseInt(x)+parseInt(y); 
console.log("Sum is",z); 
} 
</script>
 </head>
 <body> 
<form>
 <input type="" id="t1" name=""/>
 <input type="" id="t2" name=""/> 
<input type="button" onclick="sum(t1.value,t2.value)" value="Click me"/> 
</form>
 </body>
 </html>
rudy0807
  • 152
  • 1
  • 8