0

Need to get index number of the element from the array of elements

<input type="button" name="test" value="test" onclick="getindex(this)"> <!--index 0-->
<input type="button" name="test" value="test" onclick="getindex(this)"> <!--index 1-->
<input type="button" name="test" value="test" onclick="getindex(this)"> <!--index 2-->
<input type="button" name="test" value="test" onclick="getindex(this)"> <!--index 3-->
...
<script>
function getindex(obj) {
    var i = obj.index; //here is wrong. How to get index?
}
</script>
Sagar
  • 477
  • 4
  • 15
卓琮偉
  • 169
  • 1
  • 2
  • 9

4 Answers4

2

A method less prone to problems when you change the page, would be to assign the values to a data attribute:

<input type="button" name="test" value="test" onclick="getindex(this)" data-index="0"> 
<input type="button" name="test" value="test" onclick="getindex(this)" data-index="1"> 
<input type="button" name="test" value="test" onclick="getindex(this)" data-index="2"> 
<input type="button" name="test" value="test" onclick="getindex(this)" data-index="3"> 

Then retrieve the index from that data attribute:

<script>
function getindex(obj) {
    var i = parseInt(obj.dataset.index,10);
}
</script>
Kevin Sijbers
  • 814
  • 7
  • 19
1

Add an attribute called index to html button and then try to access it on button click. You can use this.

<input type="button" index='0' name="test" value="test" onclick="getindex(this)"> <!--index 0-->
<input type="button" index='1' name="test" value="test" onclick="getindex(this)"> <!--index 1-->
<input type="button" index='2' name="test" value="test" onclick="getindex(this)"> <!--index 2-->
<input type="button" index='3' name="test" value="test" onclick="getindex(this)"> <!--index 3-->

<script>
    function getindex(obj) {
        var i = obj.getAttribute('index');
    }
</script>
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

Because the element itself doesn't know anything about any indices, it is not possible this way. One alternative to solve this problem would be to create the buttons dynamically:

<script>
    for (var i = 0; i < 4; i++) {
      var onClick = function () {
        console.log(i);
      }

      var button = document.createElement('button');
      button.onclick = onClick;
      document.querySelector('body').appendChild(button); 
    }
</script>
0

You don't need to add an attribute...

here is a fiddle

<script type="text/javascript">
    function getindex(index) {
        alert(index);
    }
</script>

<input type="button" name="test" value="test" onclick="getindex(0)">
<input type="button" name="test" value="test" onclick="getindex(1)">
<input type="button" name="test" value="test" onclick="getindex(2)">
<input type="button" name="test" value="test" onclick="getindex(3)">
Charlie Martin
  • 8,208
  • 3
  • 35
  • 41