【发布时间】:2015-08-07 12:05:47
【问题描述】:
我正在使用 jQuery 自动完成功能制作搜索功能,其中数据来自 json。 搜索应该显示一个人的全名,但由于名字和姓氏在 json 中的两个不同字段中,我发现很难在自动完成下拉列表中同时显示名字和姓氏。
当一个人搜索两个值并在下拉列表中显示全名时,是否可以将两个值连接在一起?
JSON 示例:
{
"GetContactsResult": [
{
"FirstName": "John",
"LastName": "Doe",
"LocalNumber": "555000",
"MobileNumber": "555000"
},
{
"FirstName": "Jane",
"LastName": "Doe",
"LocalNumber": "555000",
"MobileNumber": "555000"
}]}
这是我的代码/html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#typedText").autocomplete({
source: function ( request, response ) {
$.ajax({
url: "data.json",
dataType: "json",
success: function (data) {
var sData = data.GetContactsResult.filter(function(v) {
var re = new RegExp( request.term, "i" );
return re.test(v.FirstName);
});
response( $.map( sData, function ( item ) {
return {
label: item.FirstName
};
}));
}
});
},
minLength: 2,
});
});
</script>
<meta charset="utf-8">
<title>click function</title>
</head>
<body>
<input id="typedText">
<input type="button" id="getValue" value="Type value">
</body>
</html>
所以为了更清楚,我试图让“John Doe”显示在自动完成中,而不仅仅是“John”。
【问题讨论】:
-
只需做
label: item.FirstName + " " + item.LastName;
标签: javascript jquery jquery-ui jquery-ui-autocomplete