Search HTML table with JS and jQuery

前端 未结 5 1476
谎友^
谎友^ 2020-12-13 11:28


I made a table and wanted to make it searchable, so I googled and looked here at starckoverflow.
But somehow, the things I\'ve found, that should work, dont wo

5条回答
  •  星月不相逢
    2020-12-13 12:18

    I found that the above solution was fine in theory (although it didn't work), but I found this to work better:

    $('#search-field').on('keyup', function(e) {
        if ('' != this.value) {
            var reg = new RegExp(this.value, 'i'); // case-insesitive
    
            $('.table tbody').find('tr').each(function() {
                var $me = $(this);
                if (!$me.children('td:first').text().match(reg)) {
                    $me.hide();
                } else {
                    $me.show();
                }
            });
        } else {
            $('.table tbody').find('tr').show();
        }
    });
    

    If you want to search more than one column then just change:

    if (!$me.children('td:first').text().match(reg)) {
    

    To:

    if (!$me.children('td').text().match(reg)) {
    

提交回复
热议问题