Jquery Autocomplete w / Categories搜索,仅限于用户选择的类别

时间:2016-08-11 08:49:08

标签: javascript jquery html jquery-ui jquery-ui-autocomplete

jquery Autocomplete demo page类别显示以下内容:

screenshot 1

我希望用户在单独的按钮(下拉列表)中选择类别(产品或人物),然后使用jquery搜索返回用户选择的类别中的匹配项。

预期结果:

screenshot 2

我是jquery的新手,但根据我的研究,我认为可以使用"函数"作为输入,如答案中所述(即使问题不同):

Jquery UI Autocomplete: search from multiple attributes of one array

但是我不知道接下来该做什么。

我目前的代码是来自官方文档的代码:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Categories</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <style>
  .ui-autocomplete-category {
    font-weight: bold;
    padding: .2em .4em;
    margin: .8em 0 .2em;
    line-height: 1.5;    
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
  <script>
  $( function() {
    $.widget( "custom.catcomplete", $.ui.autocomplete, {
      _create: function() {
        this._super();
        this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
      },
      _renderMenu: function( ul, items ) {
        var that = this,
          currentCategory = "";
        $.each( items, function( index, item ) {
          var li;
          if ( item.category != currentCategory ) {
            ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
            currentCategory = item.category;
          }
          li = that._renderItemData( ul, item );
          if ( item.category ) {
            li.attr( "aria-label", item.category + " : " + item.label );
          }
        });
      }
    });
    var data = [
      { label: "anders", category: "" },
      { label: "andreas", category: "" },
      { label: "antal", category: "" },
      { label: "annhhx10", category: "Products" },
      { label: "annk K12", category: "Products" },
      { label: "annttop C13", category: "Products" },
      { label: "anders andersson", category: "People" },
      { label: "andreas andersson", category: "People" },
      { label: "andreas johnson", category: "People" }
    ];

    $( "#search" ).catcomplete({
      delay: 0,
      source: data    
    });
  } );
  </script>
</head>
<body>

<label for="search">Search: </label>
<input id="search">

</body>
</html>

1 个答案:

答案 0 :(得分:0)

使用示例数据,还需要做更多的工作来设置数据以便更好地工作。如果您可以控制数据格式,则可以事先做好准备,以便更好地工作。

工作示例:https://jsfiddle.net/Twisty/uy5f2fta/

<强> HTML

<label>Search:</label>
<select id="categories">
  <option value="none"></option>
</select>
<input id="search">

<强>的jQuery

var data = [{
  label: "anders",
  category: ""
}, {
  label: "andreas",
  category: ""
}, {
  label: "antal",
  category: ""
}, {
  label: "annhhx10",
  category: "Products"
}, {
  label: "annk K12",
  category: "Products"
}, {
  label: "annttop C13",
  category: "Products"
}, {
  label: "anders andersson",
  category: "People"
}, {
  label: "andreas andersson",
  category: "People"
}, {
  label: "andreas johnson",
  category: "People"
}];

$(function() {
  // Set Variables
  var cats = [],
    labels = {},
    sel = $("#categories"),
    search = $("#search");

  // Sift out specific Categories
  $.each(data, function(k, v) {
    if (v.category !== "") {
      cats.push(v.category);
      console.log("Found Cat: " + v.category);
    }
  });
  $.unique(cats);
  console.log("All Cats: ", cats);

  // Set Categories into Select element
  $.each(cats, function(k, v) {
    sel.append("<option value='" + v + "'>" + v + "</option>");
  });

  // Create Object of various data
  labels.none = [];
  $.each(cats, function(k, v) {
    labels[v] = [];
  });
  for (var i = 0; i < data.length; i++) {
    $.each(cats, function(k, v) {
      if (data[i].category == "") {
        labels.none.push(data[i].label);
      }
      if (data[i].category == v) {
        labels[v].push(data[i].label);
      }
    });
  }
  $.each(labels, function(k, v) {
    $.unique(labels[k]);
  });
  console.log("All Labels: ", labels);

  // Set Autocomplete with variable data based on category selection
  search.autocomplete({
    delay: 0,
    source: function(req, res) {
      var cat = sel.val();
      var data = labels[cat];
      var results = [];
      $.each(data, function(k, v) {
        if (v.indexOf(req.term) == 0) {
          results.push(v);
        }
      });
      res(results);
    }
  });
});

我首先筛选出我们知道的数据类别。然后使用它来使用特殊的“none”选项填充Select元素。您可以返回并调整none数据以包含所有标签。

接下来,我们解析所有标签并将它们排序到一个具有子数组的对象中,每个类别的名称都作为索引。我们将使用该类别的数据填充每个数组。

最后,我们使用source的函数,以便我们可以选择要读取的数据集。 req.term是在字段中输入的数据,我们需要返回匹配数据的数组。 indexOf()的使用在这里很有帮助。当术语位于字符串的开头时,这将返回0。然后,我们将结果数组传递给res回调函数。

因此,使用您的示例,如果类别为“none”并且我们键入“an”,则会得到“anders”,“andreas”和“antal”。如果我们输入“和”,结果将按预期下降到'ansders'和'andreas'。