我在尝试使用AJAX填充自动填充字段时遇到问题。一个帐户 user 可以有多个成员。
我已经通过手动定义数组以使其工作而退后一步,但仍有问题。我认为它是我的jQuery UI脚本中的一些东西,因为它对我来说是一个很大的问号。
我尝试创建的功能是用户可以开始输入成员的名称(例如Smith, John
)并选择它,页面将impersonate the user并重新加载相同的页面但附加路径(在Smith, John
的示例中,它将返回?_switch_user=jsmith
)
HTML code:
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="search" id="search-names" class="form-control" placeholder="Enter member name">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
jQuery UI脚本:
var UserArray = [
{ "label": "Smith, John", "value": "jsmith" },
{ "label": "Doe, Jane", "value": "jdoe1990" }
];
$( "#search-names" ).autocomplete({
source: UserArray,
minLength: 2,
change: function() {
var UserArray = $(this).val();
if (!UserArray) return;
window.location = window.location + '?_switch_user=' + UserArray.value
}
});
答案 0 :(得分:1)
这应该可以解决问题:
$("#search-names").autocomplete({
source: UserArray,
minLength: 2,
select: function(event, matched) {
console.log(matched)
window.location = window.location + '?_switch_user=' + matched.item.value
}
});
答案 1 :(得分:1)
你的代码出了什么问题很简单。
1)您正在使用UserArray
作为对象数组,但在change()
函数中,您声明了另一个具有相同名称的变量。这应该是彼此不同的。
2)对象中的属性名称不应包含在&#34;&#34;。
请参阅下面的代码或此fiddle
<强> HTML 强>
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="search" id="search-names" class="form-control" placeholder="Enter member"/>
</div>
<button type="submit" class="btn btn-default">
Submit
</button>
</form>
<强>的jQuery 强>
var userArray = [
{
label: "Smith, John",
value: "jsmith"
},
{
label: "Doe, Jane",
value: "jdoe1990"
}
];
$("#search-names").autocomplete({
source: userArray,
minLength: 2,
change: function() {
var user = $(this).val();
if(!user) return;
window.location = window.location + "?_switch_user=" + user;
}
})