Jump to content

Problems while adding variables inside a function


Recommended Posts

I tried to add 2 variables inside a function.I assigned the value of var a= prompt("Enter value"); and value of var b =prompt("Enter value");.I ran the code. I entered the value of var a = 12 and the value of var b = 3. The result should come 15. But it shows 123.

The code is given below. I really need help. Its a school assignment.

<script src="javascript1.js"></script>
function q(){
var a= prompt("Enter value");
var b =prompt("Enter value");
<button onclick="q()">Click on me</button>
<p id="demo"><p>
Link to comment
Share on other sites

Items returned by the prompt function are strings so you have to convert it to a number with the "Number" function.<script>function q(){ var a = Number( prompt("Enter value") ); var b = Number( prompt("Enter value") );document.getElementById("demo").innerHTML= a + b;};</script><button onclick="q()">Click on me</button><p id="demo"><p>

Edited by kodejuice
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...