24
$("#dataTable tbody").on("click", "tr", function(event){
    alert($(this).text());
});

is this syntax is for tr's which are already on the Page ?

and if not , What is the syntax for future tr's elements ?

Charles
  • 48,924
  • 13
  • 96
  • 136
Royi Namir
  • 131,490
  • 121
  • 408
  • 714

5 Answers5

55

For future elements inside #dataTable tbody, your code should work. To delegate the click all the way up to the document, allowing the same handler for future <tr> anywhere on the page, try:

$(document).on("click", "tr", function(event){
    alert($(this).text());
});
David Hellsing
  • 97,234
  • 40
  • 163
  • 203
5

Adding to Davids accepted answer, you can also use this solution to bind multiple events to a selector as well as all future matching elements.

For example an input element.

$(document).on({
    focus:function(){
        alert($(this).val());
    },
    blur: function(){
        alert($(this).val());
    }
}, 'input[type=text]');
supajb
  • 487
  • 6
  • 11
1

This will handle all <tr>s, no matter when they were created, but only within the currently-existing #dataTable tbody.
It's equivalent to .delegate.

SLaks
  • 800,742
  • 167
  • 1,811
  • 1,896
  • So there is no difference anymore between "already in dom" vs "will be in dom" ? – Royi Namir Dec 08 '11 at 12:39
  • There are still differences but delegate(), live() and on() can handle both. – Stefan Dec 08 '11 at 12:42
  • @Stefan since 1.7 I should not use live anymore and delegate is like on.... so there is no difference anymore ......right? – Royi Namir Dec 08 '11 at 12:46
  • You´re right, you shouldn´t use `live()` since 1.7 but `delegate()` and `on()` can handle a modified DOM which `click()` doesn´t. – Stefan Dec 08 '11 at 13:38
  • @RoyiNamir there is a difference. Using syntax like `$('.container elem').on('click', function(){})` is only for current elements. Using syntax like `$('.container').on('click', 'elem', function(){})` handles future elements as well. – Gavin Oct 05 '15 at 22:11
0

You have to use jQuery'S .live() for future elements

Wrong, as this is jQuery 1.7 (and i was to fast in posting my answer).

.on() works for all (future) elements.

DKSan
  • 4,026
  • 3
  • 22
  • 34
0

From api.jquery.com/on/

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()

and from api.jquery.com/live/

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

Stefan
  • 5,468
  • 4
  • 21
  • 29