jQuery 自动完成类别选择标签和值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6716266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Autocomplete Categories Select Label and Value
提问by chrisk
Trying to get the jQuery Autocomplete with categories to return the selected value to the search field and the value to a separate input field.
尝试使用类别获取 jQuery 自动完成功能,以将所选值返回到搜索字段,并将该值返回到单独的输入字段。
I have modified the data to have a value as well as label and category.
我已将数据修改为具有值以及标签和类别。
See http://jsfiddle.net/chrisk/bM7ck/
见http://jsfiddle.net/chrisk/bM7ck/
But the value is always returned to the search field instead of the label.
但该值始终返回到搜索字段而不是标签。
回答by jk.
That's how the jquery ui autocomplete works when you supply both a label and a value. If you want the label returned to the search field, then rename the value field.
这就是当您同时提供标签和值时 jquery ui 自动完成功能的工作方式。如果您希望标签返回到搜索字段,请重命名值字段。
Updated fiddle: http://jsfiddle.net/jensbits/bM7ck/3/
回答by Andrew Whitaker
You're close, you just need to:
你很接近,你只需要:
- Add
return false
to the end of yourselect
event handler, and - Add an event handler for the
focus
event so that you can override that as well, using the label instead of the value.
- 添加
return false
到select
事件处理程序的末尾,以及 - 为事件添加一个事件处理程序,
focus
以便您也可以使用标签而不是值来覆盖它。
Here's your code updated:
这是您更新的代码:
$("#search").catcomplete({
delay: 0,
source: data,
select: function(event, ui) {
$('#search').val(ui.item.label);
$('#searchval').val(ui.item.value);
return false; // Prevent the widget from inserting the value.
},
focus: function(event, ui) {
$("#search").val(ui.item.label);
return false; // Prevent the widget from inserting the value.
}
});
Here's an updated example: http://jsfiddle.net/q2kDU/
这是一个更新的示例:http: //jsfiddle.net/q2kDU/
回答by Ismael Miguel
$(function() {
$( "#searchitems" ).autocomplete({
source: [<?php echo $search /*example for full list in php*/?>],
minLength: 2,
select: function(event, ui) {
event.preventDefault();
$("#searchitems").val(ui.item.label);
$('#searchitemvalue').val(ui.item.value);
window.location="#"; //location to go when you select an item
},
focus: function(event, ui) {
event.preventDefault();
$("#searchitems").val(ui.item.label);
$('#searchitemsvalue').val(ui.item.value);
}
});
});