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.


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

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.

var allInputs = document.getElementsByTagName('input');
        for (var i = 0; i < allInputs.length; i++) {
            if (allInputs[i].className == 'someclass') {
                allInputs[i].onmousedown = function () {
                    alert([COLOR="#FF0000"]this[/COLOR].name);
                }
            }
        }

Great thanks guys. Got it working. Thanks again.