Cucko Oooo
Cucko Oooo

Reputation: 91

Dynamic tables and DOM

I've created a table through HTML where one of the columns contains a series of buttons to add a new row, delete that specific row or move the row up or down. I'm able to add a new row but I'm having some trouble removing the same row the button was pressed on. I used an alert method to display the row index and when I click the button, it shows the row index is undefined but if I click anywhere else in that same row, it shows the correct row index!

I'm fairly new at Javascript and would like to do this using pure JavaScript.

I set an alert to figure out which row index is being called and for some reason, when I click the button, it says the row index is undefined but the next alert box shows the correct row index.

    function removeData(x) {
        var ind = x.rowIndex;
        alert(ind);
        //document.getElementById("table1").deleteRow(ind);
    }

   <table id="table1" border="2px">
            <tr>
                <th>Column 1</th> <th>Column 2</th> <th>Column 3</th> <th>Column 4</th> 
            </tr>   
            <tr id="enterData" onclick="removeData(this)">
                <td id="buttons"><input type="button" value="Remove" id="button1" onclick="removeData(this)" /> 
                    <input type="button" value="Up" id="button2" onclick="up()" />
                    <input type="button" value="Down" id="button3" onclick="down()" /> 
                    <input type="button" value="Add" id="button4" onclick="editTable()" />
                </td>
            </tr>       
        </table>

Upvotes: 1

Views: 186

Answers (1)

satchmorun
satchmorun

Reputation: 12477

You're seeing two alerts because the click event is bubbling up through the DOM.

Both your tr and an input element have onclick=removeData(this) handlers.

First the click event fires on the button (which is why rowIndex is undefined), and then it bubbles up to the tr (which is why the second alert shows you the correct value).

Upvotes: 1

Related Questions