Search code examples
javascriptpromptwindow-object

adding from the window object prompt


how do I use the window object, to add/sum two numbers, example of what I got so far - (I can add both numbers but can't get it to equal the sum?)

<html>

<head>
  <script language="JavaScript">
    var requestMsg = "Enter a number";
    userInput1 = prompt(requestMsg);
    requestMsg = "Enter another number here";
    userInput2 = prompt(requestMsg);


    alert(total = " You entered " + userInput1 + " + " + userInput2 + " which equals ");
  </script>

  <head>

    <body>

    </body>

</html>


Solution

  • So the issue I guess you are facing is that when you add the inputs (eg: 3, 2) you get 32 instead of 5. This happens because the input retrieved by prompt() is a string and it needs to be converted/typecast into a number. You can do this by the Number(input) or parseInt(input, "10") functions.

    alert(total = " You entered " + userInput1 + " + " + userInput2 + " which equals " + (Number(userInput1) + Number(userInput2)));