-1

Possible Duplicate:
Retrieve Table Row Index of Current Row

<html>
 <script>
 function addValue(a) {

      var element1  = document.createElement('tr');
      var element2 = document.createElement('td');
      var text = document.createTextNode(a);
      var table  = document.getElementById('t');
      element2.appendChild(text);
      element1.appendChild(element2);
      table.tBodies(0).appendChild(element1);
    }
</script>
Name: <input type="text" name="a">
<input type="button" value="Add" onClick='javascript:addValue(a.value)'>
<table id="t" border="1">
<tr><th>Employee Name</th></tr>
</table>
</html>

this is my code sample, now when user click on any row how can i get the rowIndex

Community
  • 1
  • 1
nithin
  • 387
  • 3
  • 9
  • 20

1 Answers1

1

I have this function, i created, it works just fine:

getIndex = function (elem, collection) {
    var index = 0;
    for(var cont = 0; cont < collection.length; cont++){
        if(collection[cont].tagName == elem.tagName)
            index++;            
        if(collection[cont] === elem)
            break;      
    }
    return index - 1;
}

you use it like: first you change a bit in the HTML:

<input type="button" value="Add" onClick='javascript:addValue(this, a.value)'>

this allows you to know which a has been clicked; then, your function:

function addValue(row, a) {
 var table  = document.getElementById('t');
 var rowIndex = getIndex(row, table);
  ....
}
André Alçada Padez
  • 10,987
  • 24
  • 67
  • 120