www.webdeveloper.com
Results 1 to 4 of 4

Thread: [RESOLVED] attr() won't work on JQuery object

  1. #1
    Join Date
    Apr 2005
    Posts
    35

    resolved [RESOLVED] attr() won't work on JQuery object

    Hello,

    I'm retrieving an element on the page with JQuery and trying to get the "value" attribute like this:

    var myVar = $("#elmId").attr("value");

    but myVar ends up being "undefined".

    I know I can get the element itself because this line works fine:

    var myVar = $("#elmId");

    Why doesn't attr() work?

  2. #2
    Join Date
    Apr 2013
    Posts
    56
    Try to use prop() or val() methods instead. See if that helps.

  3. #3
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,674
    this may happen because this element has no such inline attribute.

    Code:
    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>123</title>
    <style type="text/css">
    body{color:#000;background-color:#fff;font-family:'Bookman Old Style',Georgia,Verdana;font-size:14px;text-align:center;font-weight:bold;margin-top:300px;}
    </style>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
    $('#z').val('I AM THE VAL()');
    alert($('#z').attr('value'));
    alert($('#z').val());
    });
    </script>
    </head>
    <body>
    <input type="text" id="z" />
    </body>
    </html>

  4. #4
    Join Date
    Apr 2005
    Posts
    35
    Thanks everyone,

    The prop() and val() methods work, but the problem I was having before (which prevented any method from working) was that the script was being run before the DOM objects were available. The script was at the top of the page and it called my function (which included the code in the OP) before anything was loaded onto the page. Replacing the function call with:

    $(document).ready(MyFunction);

    did the trick. It says to call MyFunction() only when the page is ready.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles