Make search input to filter through list Jquery

后端 未结 4 693
花落未央
花落未央 2020-12-18 14:25

Hey, I am trying to create a search field that will filter or show/hide(which ever is best) the list elements based on what the user typed in and clicked the search button.

4条回答
  •  旧巷少年郎
    2020-12-18 14:59

    This uses jQuery and creates a sliding animation, too. This would be the HTML:

    List of countries

    JavaScript

    (function ($) {
      // custom css expression for a case-insensitive contains()
      jQuery.expr[':'].Contains = function(a,i,m){
          return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
      };
    
    
      function listFilter(header, list) { // header is any element, list is an unordered list
        // create and add the filter form to the header
        var form = $("
    ").attr({"class":"filterform","action":"#"}), input = $("").attr({"class":"filterinput","type":"text"}); $(form).append(input).appendTo(header); $(input) .change( function () { var filter = $(this).val(); if(filter) { // this finds all links in a list that contain the input, // and hide the ones not containing the input while showing the ones that do $(list).find("a:not(:Contains(" + filter + "))").parent().slideUp(); $(list).find("a:Contains(" + filter + ")").parent().slideDown(); } else { $(list).find("li").slideDown(); } return false; }) .keyup( function () { // fire the above change event after every letter $(this).change(); }); } //ondomready $(function () { listFilter($("#header"), $("#list")); }); }(jQuery));

    CSS is optional. JSFiddle Demo: http://jsfiddle.net/4feug/

提交回复
热议问题