Kendo UI [DropDownList] - 过滤搜索,如果找不到搜索项则显示消息

时间:2016-02-19 03:33:45

标签: jquery kendo-ui kendo-dropdown

我正在使用带有搜索过滤器的Kendo UI DropDownList ...

如果搜索项目在下拉列表中不可用,如何将搜索图标替换为“+ Add”链接和“No items available”消息...

  

Online Demo

请参阅下图以获得更多说明...... enter image description here

的jQuery

$(document).ready(function() {

    $("#products").kendoDropDownList({
        filter: "contains",
    });

    if ($('.k-list-scroller ul').length == 0){
        $('.k-list-filter .k-i-search').hide();
        $('.k-list-filter').append('<a href="#" id="newItem">+ Add</a>');
    }

    if ($('.k-list-scroller ul').length > 0){
        $('.k-list-filter .k-i-search').show();
        $('.k-list-filter #newItem').remove();
    }

});

HTML

<h4>Products</h4>
<select id="products">
    <option>Lorem</option>
    <option>Ipsum</option>
    <option>Dolar</option>
    <option>Sit amet lieu</option>
</select>

1 个答案:

答案 0 :(得分:2)

您只在页面加载时运行代码( $(document).ready())。每次文本框更新时,您都需要添加一个事件处理程序来使用您的代码。我能够为此添加一个keyup事件。

然而,一旦添加了该代码,代码就会在kendo知道下拉列表中的值发生变化之前运行。使用 delay ,我们可以暂停一下,让下拉列表正确更新。

注意:我使用500毫秒作为延迟,但该数字不是 数字。

$(document).ready(function() {
  // set up the delay function
  var delay = (function(){
    var timer = 0;
    return function(callback, ms) {
      clearTimeout (timer);
      timer = setTimeout(callback, ms);
    };
  })();
    
  $("#products").kendoDropDownList({
    filter: "contains"
  });

  // set up the event handler
  $(".k-list-filter input").keyup(function () {
    
    // wait for Kendo to catch up
    delay(function () {
      // check the number of items in the list and make sure we don't already have an add link
      if ($('.k-list-scroller ul > li').length === 0 && !($("#newItem").length)) {
        $('.k-list-filter .k-i-search').hide();
        $('.k-list-filter').append('<a href="#" id="newItem">+ Add</a>');
      }

      // check the number of items in the list
      if ($('.k-list-scroller ul > li').length > 0) {
        $('.k-list-filter .k-i-search').show();
        $('.k-list-filter #newItem').remove();
      }
        
    }, 500); // 500 ms delay before running code
  });    
});
html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/dropdownlist/serverfiltering">
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.1.112/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.1.112/styles/kendo.material.min.css" />
<script src="//kendo.cdn.telerik.com/2016.1.112/js/jquery.min.js"></script>
<script src="//kendo.cdn.telerik.com/2016.1.112/js/kendo.all.min.js"></script>
</head>
<body>

  <h4>Products</h4>
  <select id="products">
    <option>Lorem</option>
    <option>Ipsum</option>
    <option>Dolar</option>
    <option>Sit amet lieu</option>
  </select>
      
</body>
</html>