2013-03-07 66 views
3

我想设置自动填充插件,仅用于选择列表中的有效员工。我有一个Employee对象的数组,具有EmployeeID和EmployeeName。目前,我已通过将所有Employee的EmployeeName复制到数组中并将其提供给安装自动完成插件来加载EmployeeName的自动完成。通过对象数组的多个值过滤Jquery自动完成

var employeeNames = new Array(); 
for (var i = 0 ; i < employees.length ; i++) 
{ 
    employeeNames[a] = employees.Employee[a].Name; 
} 
$("#txtEmployeeName").autocomplete(employeeNames, { 
    multiple: true, 
    mustMatch: true, 
    autoFill: true 
}); 

它会做的工作,但我要的是,如果用户想要在这个文本框输入雇员,它加载的雇员建议过滤过,虽然它会显示在建议中EmployeeNames的。有没有什么办法可以实现,我记得我在某处看到它,但不记得该网站。

回答

8

jQueryUI的需要值和/或标签字段,如果使用的是一个对象:支持

多种类型:

阵列:数组可用于本地数据。有两种支持格式:一个字符串数组:[“选择1”,“选择2”]

与标签和值的属性的对象数组: [{标号:“选择1”,值:“VALUE1”} ,...]标签属性在建议菜单中显示为 。当用户选择一个项目时,该值将被插入到输入 元素中。如果仅指定一个属性 ,则它将用于两者,例如,如果您只提供值 属性,则该值也将用作标签。

来源:http://api.jqueryui.com/autocomplete/#option-source

考虑到这一点,你必须通过你的数据,包括价值属性,你只分配给名称(例如:$.each(employees, function(){ this.value = this.name }); ...)

现在你必须定义的其他事情是你想要如何过滤。这可以通过定义来源来完成。

例子:

$("#txtEmployeeName").autocomplete({ 
     source: function (request, response) { 
      var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i"); 

      var matching = $.grep(employees, function (value) { 
       var name = value.value; 
       var id = value.id; 

       return matcher.test(name) || matcher.test(id); 
      }); 
      response(matching); 
     } 
    }); 

提琴手例如:http://fiddle.jshell.net/YJkTr/

全码:

<!doctype html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>Demo</title> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" /> 
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script> 


    <script> 
     $(function() { 
      var employees = [ 
       { "value": "Tom", "id": "1" }, 
       { "value": "Stefan", "id": "2" }, 
       { "value": "Martin", "id": "3" }, 
       { "value": "Sara", "id": "4" }, 
       { "value": "Valarie", "id": "5" }, 
      ] 

      $("#txtEmployeeName").autocomplete({ 
       source: function (request, response) { 
        var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i"); 

        var matching = $.grep(employees, function (value) { 
         var name = value.value; 
         var id = value.id; 

         return matcher.test(name) || matcher.test(id); 
        }); 
        response(matching); 
       } 
      }); 
     }); 
    </script> 
</head> 
<body style="font-size: 62.5%;"> 
    <div class="ui-widget"> 
     <form> 
      <label for="txtEmployeeName">Developer:</label> 
      <input id="txtEmployeeName" /> 
     </form> 
    </div> 
</body> 
</html> 
+0

谢谢,我改了称呼,因此可以更容易地找到 – Stefan 2013-03-07 10:56:46

+0

我还有一个问题斯特凡,如何在选择事件中重新绑定自动填充。就像我想从我刚刚选择的建议中删除该项目。我怎么做? – 2013-03-07 13:16:27

+0

发现了^ – 2013-03-11 11:48:04