Results 1 to 2 of 2

Thread: Javascript question

  1. #1
    Join Date
    Sep 2005
    Posts
    4

    Javascript question

    I am taking a Javascript class this semester and I have a question about one of my projects. Basically what I need to do is ask a user for two numbers, display those numbers to the user, add them together, and display the total. I am trying to figure out what is wrong with my code:

    Code:
    <script>
     // This program asks the user different questions and echoes them back to the user
     // it then adds the numbers together and displays the sum
     
     
     
     var firstNumber = "";
     var secNumber = "";
     var numSum = firstNumber + secNumber;
     
     firstNumber = prompt("Enter a number please", "");
     //convert firstNumber to a number
     firstNumber = eval(firstNumber);
     
    secNumber = prompt("Enter another number please", "");
     //convert secNumber to a number
    secNumber = eval(secNumber);
    
    alert ("Oh.  " + firstNumber + " , "  + secNumber )
    //convert numbersum to a number
    numSum = eval(numSum);
    alert (numSum);
    //document.write(numSum);
    //numSum = alert ( "That equals );
     </script>
    The prompts work and it displays the two numbers for the user, but I can't get it to display the total. I am wondering if there is something wrong with my variables?? Any help would be appreciated

  2. #2
    Join Date
    Jun 2004
    Posts
    173
    First, don't use eval to convert a string to a number. In fact, avoid eval in general; it is one of the most inefficient methods in the entire JavaScript arsenal. Instead, use parseInt or parseFloat as in:
    Code:
    var num_str="56";
    var num=parseInt(num_str);
    Second, you are assigning a value to numSum when firstNumber and secNumber are null strings. That value will not automatically change just because you have assigned new values to the other variables. You must recalculate it before printing. Eval will not accomplish that, you must do the calculation itself.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •