0

I want to get current index array while loop. heres my code.

HTML

<input class="btn" value="Car"><br>
<input class="btn" value="Motorcycle">

Javascript

var btn= document.getElementsByClassName('btn');

    for(i=0; i < btn.length; i++){

        btn[i].addEventListener('click', function(v){

            var index = btn[i];

            document.write(index);

        }, false);
    } 

When i clicked a button the result is undefined instead 0 or 1.

DavidSlavalia
  • 23
  • 1
  • 5
  • 1
    Really! Just use `var index = this`, and you'll get the right result, but it still won't be an index ? – adeneo Jul 15 '14 at 17:00
  • 1
    anyway, where is `btn` defined? anyway, I did this: http://jsfiddle.net/69tuE/ . Perhaps that's the most efficient way to to this, instead of getting "0" or "1" you just get the **value** of it. <-- check the javascript console in the fiddle. Moreover, in my fiddle, the index variable is useless, that's cool. – briosheje Jul 15 '14 at 17:00
  • i believe this is a scope problem. `i` is not the same inside the callback. – OtotheA Jul 15 '14 at 17:00
  • `i` will be btn.length, so when you call `btn[i]` you're calling outside of the bounds, and getting undef. – scragar Jul 15 '14 at 17:01
  • i try what u said change btn[i] with this. it nothing happens. – DavidSlavalia Jul 15 '14 at 17:03
  • @DavidSlavalia: I've provided you a fiddle which actually enclose all the answers that has been posted until now. – briosheje Jul 15 '14 at 17:05
  • You should not be using `document.write` after the page has finished loading. And as adeneo said, if you want the element that was clicked, just use `this`. If you actually want the index, then see the duplicate. – cookie monster Jul 15 '14 at 17:09
  • @briosheje No, i want to get the index array not the value. i just forget to remove the value. i give a straight problem only want to get current index array. – DavidSlavalia Jul 15 '14 at 17:09
  • @DavidSlavalia: ok, there you are: http://jsfiddle.net/69tuE/1/ . I don't understand why you want to do this, but there you are ;) – briosheje Jul 15 '14 at 17:11
  • @cookie monster i try to use documentwrite( this.btn[i] ); it returns [object HTMLDivElement]. – DavidSlavalia Jul 15 '14 at 17:13
  • @briosheje yes, its work. it straight forward. thank you anyway. nice to meet you all :) – DavidSlavalia Jul 15 '14 at 17:19
  • So what's the problem? You wanted the index number instead? – cookie monster Jul 15 '14 at 17:20

0 Answers0