Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery On function for future elements? [duplicate]

Tags:

jquery

$("#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 ?

like image 733
Royi Namir Avatar asked Dec 08 '11 12:12

Royi Namir


3 Answers

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());
});
like image 124
David Hellsing Avatar answered Nov 14 '22 06:11

David Hellsing


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]');
like image 31
supajb Avatar answered Nov 14 '22 06:11

supajb


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.

like image 1
SLaks Avatar answered Nov 14 '22 05:11

SLaks