Results 1 to 5 of 5

Thread: simple operator question

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Aug 2002
    Location
    Singapore
    Posts
    254

    simple operator question

    I wanna allow user to enter 2 values then i add them up togther

    <script type="text/javascript">
    var x = prompt("Please enter a value for x","")
    var y = prompt("Please enter a value for y"," ")
    if (x != null && x != "" && y != null && y != "")
    {
    var result
    eval ("result = x" + "y")
    document.write("Your result is " + result)
    }
    </script>

    eg: i key 1 for x and 2 for y the result i get is 12 instead of 3

    pls help

    Akababy.Net... Life Redefined!

  2. #2
    Lively Member morrowasted's Avatar
    Join Date
    Aug 2003
    Location
    Houston, TX
    Posts
    118
    first of all, you need to add ; to those lines

    second of all, i dont know the answer...

    erm...

    result=eval(x+y);

    ?

    ok, well now (in Mozilla 1.5) its actually displaying something...but you're right, it is "12"... ummm..

    take a look here

    -morrowasted

  3. #3
    Fanatic Member davebat's Avatar
    Join Date
    Dec 2002
    Posts
    727
    you need to use the parseInt function so that the strings are treated as numbers and not just concatanated together

    Code:
    <script type="text/javascript">
    var x = prompt("Please enter a value for x","")
    var y = prompt("Please enter a value for y"," ")
    if (x != null && x != "" && y != null && y != "")
    {
    var result = eval (parseInt(x) + parseInt(y))
    document.write("Your result is " + result)
    }
    </script>

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Aug 2002
    Location
    Singapore
    Posts
    254
    thanks

    Akababy.Net... Life Redefined!

  5. #5
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    The eval is not necessary, just
    parseInt(x) + parseInt(y)
    suffices.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

Posting Permissions

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



Click Here to Expand Forum to Full Width