JQuery autocomplete отображает все элементы, не фильтрует при наборе - PullRequest
1 голос
/ 05 апреля 2019

Я использую плагин автозаполнения JQuery UI в своем веб-приложении.Я смог заставить его работать, но проблема в том, что всякий раз, когда я набираю текстовое поле, отображаются все элементы из моего массива.То, что я хочу сделать, это то, что я ввожу в текстовое поле, я хочу получить все соответствующие элементы при наборе.

это мой код

var products= [
              {"id":1,"value":"VITA.E D-ALPHA 400 UI X 30S","code":"00019","barcode":null,"case_cost":"168.00","pack_cost":"168.00","piece_cost":"5.60"},
              {"id":2,"value":"NATTOKIN 1000MG SOFTGELX6S","code":"0005","barcode":null,"case_cost":"0.00","pack_cost":"0.00","piece_cost":"0.00"},
              {"id":3,"value":"LIVERMARIN PLUS 1000MGX6S","code":"0006","barcode":null,"case_cost":"0.00","pack_cost":"0.00","piece_cost":"0.00"},
              {"id":4,"value":"LIVERMARIN PLUS X30S","code":"00063","barcode":null,"case_cost":"528.00","pack_cost":"528.00","piece_cost":"17.60"},
              {"id":5,"value":"NATTOKIN X 30S","code":"00065","barcode":null,"case_cost":"840.00","pack_cost":"840.00","piece_cost":"28.00"},
              {"id":6,"value":"OMEGAMAX 12X30S","code":"00067","barcode":null,"case_cost":"5472.00","pack_cost":"456.00","piece_cost":"15.20"}
             ];


$('#product_code').autocomplete({
    minLength:2,
    source : function(req,res){
        res($.map(products, function(item){
            return{
                id: item.id,
                value : item.code,
                label : item.value,
                description : item.value,
                case_cost : item.case_cost,
                piece_cost : item.piece_cost,
                pack_cost : item.pack_cost
            }
        }))
    },
    select : function(ev,ui){
        //some codes here
    },

}).focus(function() {
    $(this).autocomplete("search", $(this).val());
});

Ответы [ 2 ]

2 голосов
/ 05 апреля 2019

Фильтрация массива в обратном вызове источника , где используется Array#filter метод фильтрации, а String#includes для проверки строки содержит поисковый запрос.

var products= [              {"id":1,"value":"VITA.E D-ALPHA 400 UI X 30S","code":"00019","barcode":null,"case_cost":"168.00","pack_cost":"168.00","piece_cost":"5.60"},              {"id":2,"value":"NATTOKIN 1000MG SOFTGELX6S","code":"0005","barcode":null,"case_cost":"0.00","pack_cost":"0.00","piece_cost":"0.00"},              {"id":3,"value":"LIVERMARIN PLUS 1000MGX6S","code":"0006","barcode":null,"case_cost":"0.00","pack_cost":"0.00","piece_cost":"0.00"},              {"id":4,"value":"LIVERMARIN PLUS X30S","code":"00063","barcode":null,"case_cost":"528.00","pack_cost":"528.00","piece_cost":"17.60"},              {"id":5,"value":"NATTOKIN X 30S","code":"00065","barcode":null,"case_cost":"840.00","pack_cost":"840.00","piece_cost":"28.00"},              {"id":6,"value":"OMEGAMAX 12X30S","code":"00067","barcode":null,"case_cost":"5472.00","pack_cost":"456.00","piece_cost":"15.20"}             ];


$('#product_code').autocomplete({
  minLength: 2,
  source: function(req, res) {
    res($.map(products.filter(o => o.value.toLowerCase().includes(req.term.toLowerCase())), function(item) {
      return {
        id: item.id,
        value: item.code,
        label: item.value,
        description: item.value,
        case_cost: item.case_cost,
        piece_cost: item.piece_cost,
        pack_cost: item.pack_cost
      }
    }))
  },
  select: function(ev, ui) {
    //some codes here
  },

}).focus(function() {
  $(this).autocomplete("search", $(this).val());
});
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/jquery-ui-git.js"></script>

<input id="product_code">

С ES6 Назначение деструктуры и Array#map метод.

var products= [              {"id":1,"value":"VITA.E D-ALPHA 400 UI X 30S","code":"00019","barcode":null,"case_cost":"168.00","pack_cost":"168.00","piece_cost":"5.60"},              {"id":2,"value":"NATTOKIN 1000MG SOFTGELX6S","code":"0005","barcode":null,"case_cost":"0.00","pack_cost":"0.00","piece_cost":"0.00"},              {"id":3,"value":"LIVERMARIN PLUS 1000MGX6S","code":"0006","barcode":null,"case_cost":"0.00","pack_cost":"0.00","piece_cost":"0.00"},              {"id":4,"value":"LIVERMARIN PLUS X30S","code":"00063","barcode":null,"case_cost":"528.00","pack_cost":"528.00","piece_cost":"17.60"},              {"id":5,"value":"NATTOKIN X 30S","code":"00065","barcode":null,"case_cost":"840.00","pack_cost":"840.00","piece_cost":"28.00"},              {"id":6,"value":"OMEGAMAX 12X30S","code":"00067","barcode":null,"case_cost":"5472.00","pack_cost":"456.00","piece_cost":"15.20"}             ];



$('#product_code').autocomplete({
  minLength: 2,
  source: function(req, res) {
    res(products.filter(o => o.value.toLowerCase().includes(req.term.toLowerCase()))
      .map(({
        id,
        code,
        value,
        case_cost,
        piece_cost,
        pack_cost
      }) => ({
        id,
        value: code,
        label: value,
        description: value,
        case_cost,
        piece_cost,
        pack_cost
      })))
  },
  select: function(ev, ui) {
    //some codes here
  },

}).focus(function() {
  $(this).autocomplete("search", $(this).val());
});
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/jquery-ui-git.js"></script>

<input id="product_code">
1 голос
/ 05 апреля 2019

Follow jquery UI Документация автозаполнения интерфейса

var products= [
              {"id":1,"value":"VITA.E D-ALPHA 400 UI X 30S","code":"00019","barcode":null,"case_cost":"168.00","pack_cost":"168.00","piece_cost":"5.60"},
              {"id":2,"value":"NATTOKIN 1000MG SOFTGELX6S","code":"0005","barcode":null,"case_cost":"0.00","pack_cost":"0.00","piece_cost":"0.00"},
              {"id":3,"value":"LIVERMARIN PLUS 1000MGX6S","code":"0006","barcode":null,"case_cost":"0.00","pack_cost":"0.00","piece_cost":"0.00"},
              {"id":4,"value":"LIVERMARIN PLUS X30S","code":"00063","barcode":null,"case_cost":"528.00","pack_cost":"528.00","piece_cost":"17.60"},
              {"id":5,"value":"NATTOKIN X 30S","code":"00065","barcode":null,"case_cost":"840.00","pack_cost":"840.00","piece_cost":"28.00"},
              {"id":6,"value":"OMEGAMAX 12X30S","code":"00067","barcode":null,"case_cost":"5472.00","pack_cost":"456.00","piece_cost":"15.20"}
             ];

Например, вы можете использовать статический источник и позволить jquery обрабатывать совпадения:

$('#product_code').autocomplete({
    minLength:2,
    source :$.map(products, function(item){
            return{
                value : item.code,
                label : item.value
            }
        }),
    select : function(ev,ui){
        //some codes here
    },

}).focus(function() {
    $(this).autocomplete("search", $(this).val());
});

Или вы можете использовать большегибкий вызываемый как источник:

$('#product_code').autocomplete({
    minLength:2,
    source : function(req,res){
          var search = req.term.toLowerCase();
          res(products.reduce(function(matches, product){
             if ( -1 !== product.code.toLowerCase().indexOf(search) )
                matches.push({value:product.code,label:product.value});
             return matches;
         }, []));
    },
    select : function(ev,ui){
        //some codes here
    },

}).focus(function() {
    $(this).autocomplete("search", $(this).val());
});
...