Jump to content

[SOLVED] noob question regading varibles


JamesThePanda

Recommended Posts

hi guys

Im realy new to learning jscript

basically I want to make a litle script with 2 propts asking for 2 numbers and the it adds them both together

 

the script I made is as follows

 

<script type="text/javascript">


function add(a,b)
{
x=a+b;
return x;
}

var num1=prompt("what is number a?");
var num2=prompt("what is number b?");

alert(add(num1,num2));

</script>

I entered 1 for both the number and the ouput comes out as 11
can someone point out were im going wrong. I wanted the out put to be 2

thanks

james

Link to comment
https://forums.phpfreaks.com/topic/181830-solved-noob-question-regading-varibles/
Share on other sites

The reason it is doing that is because you are adding 2 strings together. You need to convert those strings to integers. Try this:

 

<script type="text/javascript">


function add(a,b)
{
x=parseInt(a)+parseInt(b);
return x;
}

var num1=prompt("what is number a?");
var num2=prompt("what is number b?");

alert(add(num1,num2));

</script>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.