这是我的代码
<script>
$(function() {
var availableTags1 = [
{"key": "1","name": "NAME 1"},{"key": "2","name": "NAME 2"},{"key": "3","name": "NAME 3"}
];
var availableTags2=[
{"key":"22","value":"Ahmedabad"},{"key":"23","value":"Bangalore"},{"key":"24","value":"Chandigarh"},{"key"
:"25","value":"Chennai"}];
$( "#project-name" ).autocomplete({
minLength: 0,
source: availableTags2,
select: function( event, ui ) {
$("#project-name").val( ui.item.value );
}
});
});
</script>
<input id="project-name" name="project2" />
如果我们使用availableTags2
它的工作正常。但是如果我们使用availableTags1
不起作用。我也改成了$("#project-name").val( ui.item.name );
。但它没有展示任何东西。
答案 0 :(得分:1)
使用值
更改此名称 老了:var availableTags1 = [
{"key": "1","name": "NAME 1"},{"key": "2","name": "NAME 2"},{"key": "3","name": "NAME 3"}
];
新:
var availableTags1 = [
{ "key": "1", "value": "NAME 1" }, { "key": "2", "value": "NAME 2" }, { "key": "3", "value": "NAME 3" }
];
当我们从列表中选择任何标签时,选择事件调用
这是一个例子,带有json的句柄,带有ajax调用(api调用)
$('#selcloter').autocomplete({
source: function (request, response) {
$.ajax({
url: "url",
data: "{ 'inputdate': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.name,
value: item.name,
//this is custom tag, can give any name
keyvalue: item.key
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function (event, ui) {
$(this).val(ui.item.value)
$('#HiddenFieldtosavekey').val(ui.item.KeyValue);
},
open: function () {
$(this).autocomplete("widget").css({
"width": 400
});
$(this).autocomplete('widget').zIndex(100002);
},
close: function () {
//$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
答案 1 :(得分:0)
所以availableTags1
使用这个结构
{"key": "1","name": "NAME 1"}
availableTags2
{"key":"22","value":"Ahmedabad"}
将name
更改为value
,然后就可以了。
修改强>
或者,如果您无法控制数据,则可以使用此
var tags = [],
temp = availableTags2;
for (var i = 0; i < temp.length; i++) {
tags.push({
"key": temp[i].key,
"value": temp[i].value ? temp[i].value : temp[i].name ? temp[i].name : ''
});
}
availableTags2 = tags;
干杯!