SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Addict
    Join Date
    Sep 2004
    Location
    Denver
    Posts
    385
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Shouldn't eval() work in this example?

    Greetings, Shouldn't eval() do the trick for me in this sample code. trying to get the value of the passed in attribute. I'm getting a "Object doesn't support this property or method"
    Code:
    <html><head>
    <script language="javascript" type="text/javascript">
    function getAttValue(Attribute) 
    {
    	var test = document.getElementById('div1');
    	alert(test.eval(Attribute));
    }
    </script>
    </head>
    
    <body onload="getAttValue('align');">
    <div id="div1" align="left">hello world...</div>
    </body></html>
    Thanks.

  2. #2
    Caveat surfer Buddy Bradley's Avatar
    Join Date
    May 2003
    Location
    Cambridge, UK
    Posts
    2,366
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No, eval isn't a method of an object, it is a global function. You use it like this:
    Code:
    eval ("alert(test." + Attribute + ");");

  3. #3
    SitePoint Addict
    Join Date
    Sep 2004
    Location
    Denver
    Posts
    385
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Buddy, Thanks for the clarification.

  4. #4
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,784
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    A better way would be:

    Code:
    var tmpFunc = new Function("alert(test." + Attribute + ");");
    tmpFunc();
    or even better still

    Code:
    alert(test[attribute]);
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  5. #5
    SitePoint Addict
    Join Date
    Sep 2004
    Location
    Denver
    Posts
    385
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I like the last one... thanks Stephen.

  6. #6
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,784
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    One or other of the two forms of code that I showed can almost always be used to avoid the need to use eval() which results in faster running code and removes the security issues associated with eval().
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">


Bookmarks

Posting Permissions

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