4 Leave Cover
4 Leave Cover

Reputation: 1276

Datatable show hidden elements upon search successful

I have some HTML elements which are hidden by default until user try to search for it. I am thinking to change the class of the element to show when the DataTable search completed (if found).

Refer to the jQuery code below where I implement the search, what is the next step to show the parent or the container of it?

E.g. if the search key is c or cc or ccc, how to show its parent (in this case is <li class="show">)?

jQuery

$("#txtSearch").on('keyup keypress blur change', function(e) { 
    var val = $(this).val();
    $('#mytable').DataTable().search(val).draw();
});

HTML

<li class="hide">aaa</li>
<li class="hide">bbb</li>
<li class="hide">ccc</li>

Upvotes: 0

Views: 169

Answers (1)

ThivankaW
ThivankaW

Reputation: 540

Take a look at this code Snipp,Iterate over the Hide classes and extract the inner text then compare your search results.

    $("#txtSearch").on('keyup keypress blur change', function(e) { 

        var val = $(this).val();
        var numItems = $('.hide').length ;

            for(var count = 1; count<=numItems;count++){

                var index = count-1;
                var searchResult = $(".hide:eq("+index+")").text(); 

                if(val.indexOf(searchResult) > -1){

                    $(".hide:eq("+index+")").removeClass("hide").addClass("show");
                }

                else{

                    $(".hide:eq(" + index + ")").removeClass("show").addClass("hide");
                }
            }

        $('#mytable').DataTable().search(val).draw();

    });

Upvotes: 1

Related Questions