Function to add two numbers

This is my code:

Why my function isn’t working?
.

Enter number 1

Enter number 2

ADD

I have also attached the screenshot of my code.
Please help!

Hi @muskanmotwani.1211 ,
Make the following changes

num1= parseInt(document.getElementById("num1").value);
        
   num2=parseInt(document.getElementById("num2").value);

The parseInt() function parses a string argument and returns an integer. By default, document.getElementById(id).value will return a string so you’ll have to convert it into an integer.

<!DOCTYPE html>
<html>
<head>
	<title>
		
	</title>
</head>
<body>
	<p>Enter number 1 <input id=" num1"> <div> Enter number 2 <input id="num2"></div></p>
	<button onclick="sum()">ADD</button>
	<script type="text/javascript">
		function sum()
		{
		int num1= parseInt(document.getElementById("num1").value);
		int num2=parseInt(document.getElementById("num2").value);   
	    int addition= (num1 + num2);
		alert(addition);
	}</script>

</body>
</html>
```strong text

STILL NOT WORKING
Please try running it…

Hi @muskanmotwani.1211
Try to run this code.I had run my side and it gives proper output
The code

1 Like

Hi @muskanmotwani.1211 ,
There’s no such keyword as int in javascript. As javascript is a dynamically typed language, you need not specify types explicitly.
Correct code:

num1= parseInt(document.getElementById("num1").value);
num2=parseInt(document.getElementById("num2").value);   
addition= (num1 + num2);

still not working… :frowning:
Buthow thanks for the information. I will take care of that in future.

Thanks! :slight_smile:
But in my case why my alert function is not working…
I mean I want to print output with the help of alert… I know my code is not as beautiful and organised as yours but I want to know the error in my case. Thanks for replying :slight_smile:

<!DOCTYPE html>
<html>
<head>
	<title>
		
	</title>
</head>
<body>
	<p>Enter number 1 <input id=" num1"> <div> Enter number 2 <input id="num2"></div></p>
	<button onclick="sum()">ADD</button>
	<script type="text/javascript">
		function sum()
		{
		 num1 = (document.getElementById("num1").value); 
		 num2 = (document.getElementById("num2").value);   
	     addition = parseInt(num1) + parseInt(num2);
		 alert(addition);
	}
	</script>
	
	
	

	 

</body>
</html>

Hi @muskanmotwani.1211 ,

You have put a blank space before num1 (<input id=" num1">). Please make it <input id="num1">.

Also, close the body and HTML tag. Do let me know if you need any other help.