https://jsfiddle.net/shucode/xxbkrowr/
对于填充的每个值,我希望它在下拉列表中显示相关标签。
我已经尝试但是列表附加了所有结果,而不仅仅是我需要的结果。
请看我的小提琴
$("#two").autocomplete({
source: availableTags,
focus: function (event, ui) {
$("#two").val(ui.item.value);
return false;
},
select: function (e, ui) {
$("#two").val(ui.item.value);
$.each(availableTags, function (key, value) {
var option = $('<option />').val(value.label).text(value.label);
$("#jobTypeD").append(option);
});
share = ui.item.label;
alert(share);
return false;
},
minLength: 0,
autofocus: true
});
答案 0 :(得分:1)
我修改了你的小提琴,这是工作DEMO
现在只会在下拉列表中添加自动填充中选择的值,并且不会添加重复项。这是修改后的JS代码:
$(function() {
var availableTags =
[
{ "id": "2", "value": "CCTV / Satellites / Alarms", "label": "Aerial \u0026 satellite dish installation" },
{ "id": "2", "value": "CCTV / Satellites / Alarms", "label": "Burglar, security \u0026 intruder alarm installation" },
{ "id": "2", "value": "CCTV / Satellites / Alarms", "label": "CCTV installation" },
{ "id": "2", "value": "CCTV / Satellites / Alarms", "label": "Digital Home Network" },
{ "id": "2", "value": "CCTV / Satellites / Alarms", "label": "Fire alarm installation" },
{ "id": "2", "value": "CCTV / Satellites / Alarms", "label": "Sound \u0026 Audio Visual Installation" },
{ "id": "3", "value": "Bathroom Fitter", "label": "Fit Bath" }
];
$("#two").autocomplete({
source: availableTags,
focus: function (event, ui) {
$("#two").val(ui.item.value);
return false;
},
select: function (e, ui) {
$("#two").val(ui.item.label);
//check if selected value already exists in the dropdown, if not then append the option to the dropdown
if($("#jobTypeD option").filter(function (i, o) { return o.value === ui.item.label; })
.length <= 0)
{
var option = $('<option />').val(ui.item.label).text(ui.item.label);
$("#jobTypeD").append(option);
alert("selected value is now added to the dropdown");
}
else {
alert("The selected value already exists in the dropdown and is dulicate. So it will not be added to the dropdown.");
}
/*$.each(availableTags, function (key, value) {
var option = $('<option />').val(value.label).text(value.label);
$("#jobTypeD").append(option);
});*/
share = ui.item.label;
//alert(share);
return false;
},
minLength: 0,
autofocus: true
});
});