0

Here's my code

for(var i = 0; i<tabs.length; i++)
        {
                alert(tabs[i].getAttribute('value'));
                tabs[i].onclick = function() {
                        alert("clicked");
                        alert(tab[i].getAttribute('value'));
                };
        }

This is all in the window.onload function. The first alert works, i.e. the value of each input element is alerted when the page loads. Then, when I click one of the buttons, "clicked" is alerted, but not the value attribute.

Say I have three tabs with the values "home", "about", and "contact". Is there a way to have access to (in this case, simply alert) the value (or any other) attribute when they're clicked without manually writing each onclick method?

Thanks

user3391564
  • 576
  • 1
  • 5
  • 16

2 Answers2

2

Did You try with:

this.getAttribute('value') 

instead of

tab[i].getAttribute('value')?
Gonzalo Bahamondez
  • 1,371
  • 1
  • 16
  • 37
2

I think you meant

tabs[i].getAttribute('value')

instead of

tab[i].getAttribute('value')

Either ways, The problem here is that the value of i is long changed before the click events are fired.

The simplest solution is to wrap the code with (function (i) { & })(i);

This works as a new copy of i is created & passed to the click event.

Here is a DEMO with your code. And this DEMO after the changes.

Updated code:

for (var i = 0; i < tabs.length; i++) {
        alert(tabs[i].getAttribute('value'));
        (function (i) {
            tabs[i].onclick = function () {
                alert("clicked");
                alert(tabs[i].getAttribute('value'));
            }
        })(i);
    }
loxxy
  • 12,990
  • 2
  • 25
  • 56