Jump to content
Sign in to follow this  
debakun

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.

<html>
<head>
<script src="javascript1.js"></script>
</head>
<script>
function q(){
var a= prompt("Enter value");
var b =prompt("Enter value");
document.getElementById("demo").innerHTML=a+b;
};
</script>
<button onclick="q()">Click on me</button>
<p id="demo"><p>

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...