将值设置为jquery自动完成combobox

我正在使用jquery自动完成combobox ,一切都很好。 但我也希望通过JavaScript设置特定值,如$("#value").val("somevalue")并设置为select元素,但输入元素中没有自动完成更改。

当然,我可以直接选择此输入并设置值,但是还有其他一些方法吗? 我尝试设置绑定到this.elementthis.element.bind("change", function(){alert(1)})但它没有效果。 我不知道为什么。

编辑

我发现了这种情况的解决方法。 但我不喜欢它。 我已经为ui.combobox的_create函数添加了以下代码

 this.element.bind("change", function() { input.val( $(select).find("option:selected").text()); }); 

当我需要更改值时,我可以使用$("#selector").val("specificvalue").trigger("change");

这个演示是你在寻找什么?

该链接将jQuery UI自动完成的值设置为Java 。 焦点保留在输入上,以便可以使用普通键盘事件来导航选项。

编辑:如何添加另一个function到combobox如下:

 autocomplete : function(value) { this.element.val(value); this.input.val(value); } 

并使用您要设置的值调用它:

 $('#combobox').combobox('autocomplete', 'Java'); 

更新的演示

我找不到任何可用的现有function来做你想要的,但这似乎对我很好。 希望它更接近你需要的行为。

我设法快速而肮脏地设置了价值。 但是,您确实需要知道要在下拉列表中显示的项目的值和文本。

 var myValue = foo; // value that you want selected var myText = bar; // text that you want to display // You first need to set the value of the (hidden) select list $('#myCombo').val(myValue); // ...then you need to set the display text of the actual autocomplete box. $('#myCombo').siblings('.ui-combobox').find('.ui-autocomplete-input').val(myText); 

@andyb,我想重写:

  autocomplete: function (value) { this.element.val(value); var selected = this.element.children(":selected"), value = selected.val() ? selected.text() : ""; this.input.val(value); } 

我真的很喜欢andyb所做的事情,但是我需要它在事件处理方面做一些事情才能处理触发变更事件,因为“选中”在输入输入或失去焦点时无法处理(击中标签或鼠标点击)。

因此,使用andyb作为基础以及最新版本的jQuery Autocomplete脚本,我创建了以下解决方案: DEMO

  • 输入:如果菜单可见,则选择第一个项目
  • 焦点丢失:部分匹配触发未找到消息并清除条目(jQuery UI),但完全类型的答案“选择”该值(不具有案例敏感性)

如何使用Change方法:

 $("#combobox").combobox({ selected: function (event, ui) { $("#output").text("Selected Event >>> " + $("#combobox").val()); } }) .change(function (e) { $("#output").text("Change Event >>> " + $("#combobox").val()); }); 

希望这有助于其他需要额外更改事件function的人来弥补“选定”留下的空白。

http://jsfiddle.net/nhJDd/

 $(".document").ready(function(){ $("select option:eq(1)").val("someNewVal"); $("select option:eq(1)").text("Another Val"); $("select option:eq(1)").attr('selected', 'selected'); }); 

这是一个工作示例和jquery,我假设您想要更改选择的值,更改其文本面并在页面加载时选择它?

尝试2:

这是另一个小提琴: http : //jsfiddle.net/HafLW/1/ ,你的意思是你选择一个选项,然后你想将该值附加到输入区域的自动完成?

 $(".document").ready(function(){ someString = "this,that"; $("input").autocomplete({source: someString.split(",")}); $("select").change(function(){ alert($(this).val()+" appended"); someString = someString+","+$(this).val(); $("input").autocomplete({source: someString.split(",")}); }); });