Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    New to the CF scene
    Join Date
    Dec 2005
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Exclamation trying to eval a math entry in a text field

    Hello,

    I am trying to do simple math equations in a text field and then have the answer put into a different text field. I was following a "simple tutorial" but i think that some of the code was left out. Here is what I have:

    Code:
    <form name="example">
    <input type="text" size="20" name="calculator">
    <input type="button" name="Calc" value="Calulate" onclick="value()">
    <input type="reset" name="rest" value="Reset">
    <br>Answer:<input type="text" size="20" name="answer">
    </form>
    
    <script type="text/javascript">
    <!--
    function value()
    {
       document.example.answer.value = eval(document.example.calculator.value)
    }
    //-->
    </script>
    When I press the button nothing happens and my page displays "Error on Page" in the bottom left of the page. Can someone suggest what I may be missing? Or perhaps where I could look up the eval function that the tutorial uses? Does it matter if the form is created before the script stuff? Perhaps my onClick event is not recognizing the value() function because the script code is created afterwards.
    Last edited by CodeGnome; 12-28-2005 at 09:40 PM.

  • #2
    New to the CF scene
    Join Date
    Dec 2005
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I did some more debugging and found the problem. It seems that it did not like the function name i was using of value(). I guess that I will need to be careful of reserved words.

    Perhaps someone has a better suggestion on how i could do this?

  • #3
    Kor
    Kor is offline
    Red Devil Mod Kor's Avatar
    Join Date
    Apr 2003
    Location
    Bucharest, ROMANIA
    Posts
    8,478
    Thanks
    58
    Thanked 379 Times in 375 Posts
    1. Yes, value is a reserved word. Avoid using reserved javascript words when naming functions or variables. simplu chanhe the name of that function. myValue(), for instance. Keep in mind that javascript is case sensitive.

    2. You don't need to evaluate a value when asign it. Simply assign the value

    document.example.answer.value = document.example.calculator.value

    and, anyway, avoid using eval() function. It is not trusty and it might slower the CPU. There are always other methods (square brackets notation, for instance) to use instead.

    3. don't forget that, with few exception (offset position/size), all the elements' attributes return strings as values. So that if you need a math substraction/adding you must first transform them into numbers. Number() method is one way.
    KOR
    Offshore programming
    -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

  • #4
    Regular Coder
    Join Date
    Sep 2005
    Posts
    535
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Kor's warnings about using the eval function are good to heed for most purposes... However, in this example, I think you would need to use eval...

    For example, if calculator.value="2+2", using Kor's example of just setting the .value attributes equal to each other would result in answer.value="2+2" whereas if you had:
    Code:
     document.example.answer.value = eval(document.example.calculator.value);
    then answer.value="4";

    Where Kor's warnings come into play is when the user may type in a number and the js code uses that number as a part of a variable name. For example, let's say you had some shopping-cart script that allowed the user to delete a particular line-item by having the user type in the corresponding number:
    Code:
    Item #        Item Description          Price
    1               Apple                   $0.30
    2               Bananna                 $0.15
    3               Steak                   $5.50
    4               Cherry                  $0.50
    
    Enter Item to Delete: 3
    Inside the code, the programmer may have written something like:
    Code:
    // In the HTML:
    <form name="myShoppingCart">
      <table>
        <tr name="Heading"
          <td>Item #</td>
          <td>Item Description</td>
          <td>Price</td>
        </tr>
        <tr name="Item1">
          <td>1</td>
          <td>Apple</td>
          <td>$0.30</td>
        </tr>
        ....
      </table>
      Enter Item to Delete:&nbsp;<input type="text" name="delItemNumber" onchange="deleteItem">
    </form>
    
    // In javascript
    function deleteItem()
    {
      eval("document.myShoppingCart.Item"+document.myShoppingCart.delItemNumber.value+".innerHTML=''");
    }
    Because eval() is slow (and you are not actually needing any mathematical operation performed), it would've been better to write the function in bracket notation than to use eval():
    Code:
    function deleteItem()
    {
      document.forms['myShoppingCart'].elements['Item'+document.forms['myShoppingCart'].elements['delItemNumber'].value].innerHTML="";
    }
    An even better solution would be to use DOM methods, which use an element's id property instead of its name in order to address specific elements:
    Code:
    function deleteItem()
    {
      document.removeNode(document.getElementById('Item'+document.getElementById('delItemNumber').value));
    }
    Notice how the last example was able to address specific items from the document without having to drill-down through the form in order to get there...
    Last edited by Pyth007; 12-30-2005 at 09:38 PM.
    If you want answers, write a smart question.

    Yes, someone probably does know how...

    Oh, and if you want to learn, STFW!

  • #5
    Kor
    Kor is offline
    Red Devil Mod Kor's Avatar
    Join Date
    Apr 2003
    Location
    Bucharest, ROMANIA
    Posts
    8,478
    Thanks
    58
    Thanked 379 Times in 375 Posts
    For example, if calculator.value="2+2", using Kor's example of just setting the .value attributes equal to each other would result in answer.value="2+2" whereas if you had:
    Even in this case you may use other methods than eval(). For instance Number()

    document.example.answer.value = Number(document.example.calculator.value);
    KOR
    Offshore programming
    -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

  • #6
    Regular Coder
    Join Date
    Sep 2005
    Posts
    535
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I disagree. This test code shows the difference:
    Code:
    <html><head>
    <title>Eval vs. Number Example</title>
    <script>
    	function calcQuestion()
    	{
    		document.getElementById("answerEval").value=eval(document.getElementById("question").value);
    		document.getElementById("answerNum").value=Number(document.getElementById("question").value);
    	}
    </script>
    </head>
    <body>
    	Question Textbox: <input type="text" id="question" /><br />
    	Answer Textbox (using Number): <input type="text" id="answerNum" /><br />
    	Answer Textbox (using eval): <input type="text" id="answerEval" /><br />
    	<input type="button" value=" Calculate " onclick="calcQuestion();" />
    </body>
    </html>
    If you type in "2+2" into the "question" textbox and click on the button, you'll get "NaN" for Number() but will get the correct answer ("4") in the eval's answer textbox (tested in both IE and FF).

    Along these lines, however, notice that in my "shopping cart" example in my earlier post, I never changed the "Item to delete" textbox value to a number. If for some reason you did need to use the .value as a number, then you will (or should) use the Number() method to convert it to a number first.
    If you want answers, write a smart question.

    Yes, someone probably does know how...

    Oh, and if you want to learn, STFW!

  • #7
    Kor
    Kor is offline
    Red Devil Mod Kor's Avatar
    Join Date
    Apr 2003
    Location
    Bucharest, ROMANIA
    Posts
    8,478
    Thanks
    58
    Thanked 379 Times in 375 Posts
    I see what you mean. Yet i strongly belive that always there are ways, html or javascript, to avoid eval(). For instance, why afford user to type 2+2? Let the code to do the add....
    KOR
    Offshore programming
    -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*


  •  

    Posting Permissions

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