将值设置为jquery自动完成组合框

xan*_*dox 10 javascript jquery jquery-ui jquery-ui-autocomplete

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

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

编辑

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

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

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

and*_*dyb 27

这个演示,你在找什么?

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

编辑:如何添加另一个功能到组合框如下:

autocomplete : function(value) {
    this.element.val(value);
    this.input.val(value);
}
Run Code Online (Sandbox Code Playgroud)

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

$('#combobox').combobox('autocomplete', 'Java'); 
Run Code Online (Sandbox Code Playgroud)

更新的演示

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


sea*_*tzg 5

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

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);
Run Code Online (Sandbox Code Playgroud)


小智 5

@andyb,我认为重写:

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

        var selected = this.element.children(":selected"),
                value = selected.val() ? selected.text() : "";
        this.input.val(value);
    }
Run Code Online (Sandbox Code Playgroud)