0

The code will search for element inside the collapsible div. For search the keypress event will search the data in collapsible using jquery. If the term is found, only that collapsible tree chain should be shown, others should be hidden.

$(document).ready(function(){
    $("#searchbox").keypress(function(){
        $("div.collapse").collapse("hide"); //this will reset the div to hidden so that only search term is displayed
        var search = $("#searchbox").val();
        $("div.collapse").find(":contains("+search+")").parent().collapse("show");
    });
});

JSFiddle link: https://jsfiddle.net/zvn1bsxd/

The problem is, the search is working only for odd keyup events. When you type 2nd time/ 4th time and so on, all the div are hidden. I am having trouble to determine why this is happening.

The One
  • 35
  • 4

1 Answers1

0

There is no value in #searchbox during first keypress. keyup instead of keypress to the rescue.

*updated

    $(document).ready(function () {
        $("#searchbox").keyup(function () {
            $("div.collapse").each((_, div) => {
                const match = $(div).text().includes($(this).val());

                $(div).collapse(match ? "show" : "hide")
            })
        });
    });

*updated pt.2

enter image description here

You've got duplication. Fires code daclared in HTML section only

Due to transition time collapse toggling is asynchronous. There is no sense to call .collapse('hide') and .collapse('show') on same element in one tick. Real DOM mutations happens later.

Eugen Govorun
  • 3,006
  • 1
  • 11
  • 12
  • Oh I feel stupid now, did not see the code duplication.. thanks for your help, works like a charm! – The One Oct 15 '19 at 08:44
  • Not at all. Have a nice day. – Eugen Govorun Oct 15 '19 at 08:46
  • Hi, can you help me one more time? Is it possible to highlight the search result in yellow ([like this](https://imgur.com/gwcdqQ8))? I tried so much with your code but couldn't get it to work. – The One Nov 27 '19 at 10:48
  • 1
    Hello. It is possible, but not easy. I have no time to implement selfmade function, besides it is not good idea. Use some existing plugin. Read more: https://stackoverflow.com/questions/119441/highlight-a-word-with-jquery and https://stackoverflow.com/questions/19720984/search-and-highlight-in-jquery – Eugen Govorun Nov 27 '19 at 14:41