Web Pogrammer
Web Pogrammer

Reputation: 117

make table rows clickable using jQuery

In an ASP.NET web page, I have a table that shows results from a database query. In the same page, I have a form that adds a row to the database as well as displays the row at the end of table. I used jQuery ajax to insert the record to the database and if it's successful then I created a <tr> <td> ... </td> </tr> element and appended this element to the table using jQuery. This works fine. Now I want to make the table rows clickable. I tried it using $('#table-name tr').click(function () { alert ("hello"); });

Click function doesn't work for the rows that I added using the form. Is there any workaround? How can I make all rows clickable?

Upvotes: 1

Views: 3004

Answers (3)

Travis J
Travis J

Reputation: 82287

The reason that the click event does not work for those elements is that the event handler was issued only once, before the elements existed on the DOM.

In order to have the click event exist for elements which are added in the future as well, you should use on, this will allow the handler to be assigned to the dynamically added elements. Make sure to include the 'tr' which will create a delegate function to handle the event for future elements.

$('#table-name tr').on('click', 'tr', function () { alert ("hello"); });

Another option would be to assign the click event to the element before you dynamically add it to the page.

success: function(results){
 var newRow = document.createElement("tr");
 //manipulate newRow with results
 $(newRow).click(function(){ alert("hello") });
 //append newRow
}

Upvotes: 1

Jim S.
Jim S.

Reputation: 1160

Use jquery on instead of click. The problem is that click events are only attached when the page loads.

$('#table-name').on('click', 'tr', function() {alert('hello');});

Jquery on method waits for events to propagate up from child elements.

Upvotes: 1

Blender
Blender

Reputation: 298176

$('#table-name tr') returns only the <tr> elements that exist when you call that selector. If you add new rows dynamically, they won't be accounted for.

jQuery has special syntax to take care of dynamically generated elements:

$('#table-name').on('click', 'tr', function() {
    alert('Hello');
});

Upvotes: 4

Related Questions