Tah*_*qui 3 jquery jquery-ui autocomplete jquery-autocomplete
我想设置自动完成插件,仅选择列表中的有效员工.我有一个Employee对象数组,有EmployeeID和EmployeeName.目前,我已经通过复制数组中所有Employee的EmployeeName并将其提供给设置自动完成插件来加载EmployeeName的自动完成.
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
});
Run Code Online (Sandbox Code Playgroud)
它将完成工作,但我想要的是,如果用户想要在此文本框中输入EmployeeID,它也会在EmployeeID上加载建议过滤,尽管它会在建议中显示EmployeeNames.有什么方法可以实现,我记得我在某个地方看到它,但不记得网站.
如果您正在使用对象,jQueryUI需要值和/或标签字段:
支持多种类型:
数组:数组可用于本地数据.有两种支持的格式:字符串数组:["Choice1","Choice2"]
具有label和value属性的对象数组: [{label:"Choice1",value:"value1"},...] label属性显示在建议菜单中.当用户选择项目时,该值将插入到input元素中.如果仅指定了一个属性,则它将用于两者,例如,如果仅提供值属性,则该值也将用作标签.
资料来源:http://api.jqueryui.com/autocomplete/#option-source
考虑到这一点,你必须采用你的数据,包括你刚刚分配给名称的value属性(例如$.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);
}
});
Run Code Online (Sandbox Code Playgroud)
小提琴手的例子: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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10421 次 |
| 最近记录: |