简体   繁体   中英

Filter list on click instead of on input or keyup

I found a javascript that allows a user to search my tree menu. However, I need it to work only on a button click and not as the user types. I know how to create the button and and add the OnCLick to it but I cannot figure out how to alter my working script to run only when the button is clicked.

Here is the working script (I have to give the li tag a class so the script doesn't try and search other lists on the page):

<script type="text/javascript">
$(document).ready(function () {
    $("#search").on("input", function () {
        if (this.value.length > 0) {
            $("li.menusearch").hide().filter(function () {
                return $(this).text().toLowerCase().indexOf($("#search").val().toLowerCase()) != -1;
            }).show();
      }
        else {
            $("li.menusearch").show();
        }
    });
});

Here is the input

<input type="search" id="search" name="search"/> 

To adjust your script to work on a button click, adjust it as follows (with #button corresponding to the id of your button):

 $(document).ready(function () {
    $("#button").on("click", function () {
       if ($("#search").val().length > 0) {
           $("li.menusearch").hide().filter(function () {
              return $(this).text().toLowerCase().indexOf($("#search").val().toLowerCase()) != -1;
        }).show();
       }
       else {
          $("li.menusearch").show();
       }
   });
});

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