...

View Full Version : How to get the current row clicked in javascript



xaverian
10-01-2012, 02:02 PM
Hi ,

I have a html table with some rows. Each row has a 'remove row' button in the end as <td>.
Now I want that corresponding row to be deleted if the 'remove row' button is clicked.
Let us consider the table name is "mytable"

The code is like :

<td> <input type = 'button' value = 'remove row' onclick = remRow() name = remove_i > </td>

function remRow()
{

document.getElementById("mytable").deleteRow(3);

}Right now, I passed hard-coded value '3' to deleteRow in order to delete the third row. But how can I dynamically get the row number as and when a row is clicked and delete it.

Please help. Thanks.

WolfShade
10-01-2012, 02:06 PM
Give the button an id (cannot start with a number, has to be a letter or underscore).

onclick = "remRow(this.id);"

function remRow(id){
.. add code to isolate the number..

xelawho
10-01-2012, 02:50 PM
<td><input type = 'button' value = 'remove row' onclick = "remRow(this)" name = remove_i ></td>

<script type="text/javascript">
function remRow(cell){
document.getElementById("mytable").deleteRow(cell.parentNode.parentNode.rowIndex);
}
</script>

Logic Ali
10-01-2012, 03:12 PM
Give your table the ID 'myTable', then put this below it:


<script type='text/javascript'>

( function( id )
{
var elem = document.getElementById( id ),
el = elem.addEventListener;

elem[ el ? 'addEventListener' : 'attachEvent' ]( el ? 'click' : 'onclick', f, false );

function f( evt )
{
var srcElem = evt.target || evt.srcElement;

if( srcElem.type && srcElem.type == 'button' && srcElem.value.toLowerCase() == 'remove row' )
{
while( srcElem && srcElem.nodeName != 'TR' )
srcElem = srcElem.parentNode;

if( srcElem )
srcElem.parentNode.removeChild( srcElem );
}
}
})( 'myTable' );

</script>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum