0

I have a table on which the user can select a row. I've made some CSS to highlight the selected row. The user can add rows to the original table. The probelm is that the added rows are not highlighted when selected.

HTML PART :

<table class="table_to_fill" id="table_id">
        <thead>
                <tr>
                    <th> title 1 </th>
                    <th> title 2 </th>
                </tr>
        </thead>
        <tbody>

            <tr>
                   <td>old row 1</td>
                   <td>old row 1</td>
            </tr>
            <tr>
                   <td>old row 2</td>
                   <td>old row 1</td>
            </tr>

        </tbody>
</table>

CSS :

.table_to_fill tr:hover, .table_to_fill tr.selected {
background-color: #1E90FF;
color : #fff;
font-weight : bold;}

Javascript :

$(".table_to_fill tr").click(function(){
$(this).addClass("selected").siblings().removeClass("selected");
});

//to add rows
$("#add_row_button").click(function(){
$('#table_id tr:last').after('<tr><td>new row</td><td>new row</td></tr>');
});

So what I'm doing wrong ? Thanks for any help.

blackbishop
  • 30,945
  • 11
  • 55
  • 76

1 Answers1

3

Use delegated event as the rows are added to DOM after DOM ready so event will not fire on newly added rows:

$(".table_to_fill").on('click','tr',function(){
$(this).addClass("selected").siblings().removeClass("selected");
});

FIDDLE EXAMPLE

You can understand the jquery Event Delegation from here

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • @blackbishop: The fundamental issue was that you were binding to the `click` event on *specific elements*. So the new elements that were added didn't have the event bound. Ehsan's solution using event delegation binds the `click` on the **table** instead. – T.J. Crowder Aug 03 '14 at 10:55
  • Agreed with @T.J.Crowder.. OP was binding to tr and it was binded to the ones that were available at DOM ready – Ehsan Sajjad Aug 03 '14 at 10:56