jQuery自动完成类别选择标签和值

尝试使用类别获取jQuery自动完成function,将选定的值返回到搜索字段,将值返回到单独的输入字段。

我已将数据修改为具有值以及标签和类别。

见http://jsfiddle.net/chrisk/bM7ck/

但是值始终返回到搜索字段而不是标签。

这就是当你提供标签和值时jquery ui自动完成的工作方式。 如果要将标签返回到搜索字段,请重命名值字段。

更新小提琴: http : //jsfiddle.net/jensbits/bM7ck/3/

你很亲密,你只需要:

  1. return false添加到select事件处理程序的末尾,并且
  2. focus事件添加事件处理程序,以便您也可以使用标签而不是值来覆盖它。

这是你的代码更新:

 $("#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. } }); 

这是一个更新的例子: http : //jsfiddle.net/q2kDU/

 $(function() { $( "#searchitems" ).autocomplete({ source: [], 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); } }); });