debakun Posted January 10, 2015 Share Posted January 10, 2015 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> Link to comment Share on other sites More sharing options...
kodejuice Posted January 10, 2015 Share Posted January 10, 2015 (edited) 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 January 10, 2015 by kodejuice 1 Link to comment Share on other sites More sharing options...
debakun Posted January 11, 2015 Author Share Posted January 11, 2015 Thank you very much for your help. I really appreciate it Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now