SpanTag
SpanTag

Reputation: 203

jquery, cannot select a TR after DOM manipulation

I hope somebody can help me here as I cannot figure this out. I have a table showing usernames. When I click a TR line it fetches the information by an ajax request to a PHP page that gets the content from SQL and passes it on to a form.

When the form is updated and saved the reverse is happening, sent to a PHP page by ajax, witch updates the SQL.

Then when the update is done i want the list to update it self without refreshing the page. I got this working. It is fetching the new saved content from the DB by ajax/php, and then populates the table by using .append.

BUT the problem is when the table is updated it is not possible anymore to select a TR in the table.

This is maby confusingly explained..

I have checked how the DOM looks before and after the change (with Coda/DOM tree) and they are similar at least in my eyes:

BEFORE MANUPULATION:

<table id="brukere" cellpadding="8"> 
<thead>
    <tr><td>Brukernavn</td></tr></thead>
<tbody> 
<tr id="1" onmouseover="changebgcolor(this)" onmouseout="restorebgcolor(this)"     style="background-color: white; ">
    <td>Name 1</td>
</tr>
<tr id="2" onmouseover="changebgcolor(this)" onmouseout="restorebgcolor(this)" style="background-color: white; ">
    <td>Name 2</td>
</tr>    
</tbody> 
</table>

AFTER MANIPULATION:

<table id="brukere" cellpadding="8"> 
<thead>
    <tr><td>Brukernavn</td></tr></thead>
<tbody> 
<tr id="1" onmouseover="changebgcolor(this)" onmouseout="restorebgcolor(this)">
    <td>Name 1</td> 
</tr>
<tr id="2" onmouseover="changebgcolor(this)" onmouseout="restorebgcolor(this)">
    <td>Name 2</td> 
</tr>
</tbody> 
</table>

The code I am using that work before the DOM is manipulated to select the TR is:

$("#brukere tr")
      .click(function() {

To refresh the table I first clear the TR`s:

$("#brukere").find("tr:gt(0)").remove();

And then append, the new content (data) comes as HTML from the PHP file:

$("table tbody").append(data),

Upvotes: 0

Views: 612

Answers (1)

Steve
Steve

Reputation: 8640

Well, when you do

$("#brukere").find("tr:gt(0)").remove();

you remove the tr, together with its click handler. So you either need to attach a new click handler afterwards (to the newly inserted element) or you need to use a delegate on an element that doesn't get removed, such as:

$("#brukere").on('click', 'tr', function() {...});

This will attach a click handler to the #brukere table. However, the anonymous function only gets executed if the click originated from a child tr. And since you never remove the table itself, that click handler never gets removed.

Upvotes: 4

Related Questions