简体   繁体   中英

Filtering table rows that are dynamically created (Jquery)

I have to filter a table (containing name, surname, phone and address of users) based on the input provided inside a search bar.

The content of the table is added dynamically with jquery using a form.

The following code is what I have been able to do so far regarding filtering the table rows (It works just with table rows encoded inside the html, not with table rows dynamically added with jquery).

I'm aware of the possibility of adding a delegated event handler on the .on() function, but I haven't been able to write the code that would do the job.

 //Code that filters table rows according to user's search bar content $("#search").on("keyup", function() { var value = $(this).val().toLowerCase(); $("#myTable tr").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) }); }); 
 <input type="text" id="search" placeholder="Search for names.."> <!-- This is my search bar --> 

Thanks a lot, Luca P.

You can use this function

    $("#search").on("keyup", function() {
    var input, filter, table, tr, td, i;
    input = $("#search");
    filter = input.val().toUpperCase();
    table = $("#table");
    tr = table.find("tr");

    tr.each(function () {
        var linha = $(this);
        $(this).find('td').each(function () {
            td = $(this);
            if (td.html().toUpperCase().indexOf(filter) > -1) {
                linha.show();
                return false;
            } else {
                linha.hide();
            }
        })
})
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM