Is it possible to bind a jquery filter
method to elements that don't exist yet? I have a table that is not built before page load, and a table row search that is supposed to filter out rows. Since table rows can also be added and removed, I need to be able to pre-bind the method handler. Example
class ElementSearch {
constructor($input, $elementClass){
let self = this;
this.$input = $input;
this.$elementClass = $elementClass;
this.$input.on('input', function(){
self.filterElements($(this).val());
});
return this;
}
/**
* Hide or show elements according to the search string
* @param {string} search
* @return ElementSearch
*/
filterElements(search){
search = search.toLowerCase();
let self = this;
this.$elementClass.filter(function(){
let $this = $(this);
if($this.text().toLowerCase().indexOf(search) > -1){
$this.fadeIn();
}
else {
$this.fadeOut();
}
});
return this;
}
}
In my App
I create ElementSearch
before the table is even defined or built. So I try this
this.elementSearch = new ElementSearch($input, $('body table tbody tr'));
Hoping that it will call filter
on all tr
elements even though they don't yet exist. This doesn't work (this.$elementsClass
length = 0) but if I then set it after the table is built, it works.
Is there any way to do this?