SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Nov 2012
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Get name attribute onmousedown

    Hey everyone,

    I am looping through all the inputs on a page, then trying to get the name attribute of the element that's clicked.

    Code:
    var allInputs = document.getElementsByTagName('input');
            for (var i = 0; i < allInputs.length; i++) {
                if (allInputs[i].className == 'someclass') {
                    allInputs[i].onmousedown = function () {
                        alert(allInputs[i].name);
                    }
                }
            }
    When I click on any of the inputs I get a "Uncaught TypeError: Cannot read property 'name' of undefined". What am I doing wrong?

    Thanks

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,809
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    once the loop exits the i variable contains the number of input fields - so when you reference allInputs[i] you are trying to reference the input field that comes after the last input field and since you haven't added any since you ran the loop that one doesn't exist.

    Try referencing this.name instead as at the time the mousedown event occurs this should point to the input field it is triggered on.
    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="^$">

  3. #3
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Portsmouth UK
    Posts
    1,495
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    var allInputs = document.getElementsByTagName('input');
            for (var i = 0; i < allInputs.length; i++) {
                if (allInputs[i].className == 'someclass') {
                    allInputs[i].onmousedown = function () {
                        alert(this.name);
                    }
                }
            }

  4. #4
    SitePoint Member
    Join Date
    Nov 2012
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Great thanks guys. Got it working. Thanks again.


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
  •