Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set value to jquery autocomplete combobox

I am using jquery autocomplete combobox and everything is ok. But I also want to set specific value through JavaScript like $("#value").val("somevalue") and it set to select element, but no changes in input element with autocomplete.

Of course, I can select this input and set value directly, but is it some other ways to do that? I try set bind to this.element like this.element.bind("change", function(){alert(1)}) but it was no effects. And I don't know why.

Edit

I found a workaround for this case. But I don't like it. I have added the following code to _create function for ui.combobox

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

And when I need to change the value I can use $("#selector").val("specificvalue").trigger("change");

like image 254
xandox Avatar asked Jun 01 '11 07:06

xandox


2 Answers

I managed a quick and dirty way of setting the value. But, you do need to know both the value and the text of the item that you want to display on the dropdown.

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);
like image 111
seanfitzg Avatar answered Sep 18 '22 13:09

seanfitzg


Is this demo what you are looking for?

The link sets the value of the jQuery UI autocomplete to Java. The focus is left on the input so that the normal keyboard events can be used to navigate the options.

Edit: How about adding another function to the combobox like this:

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

and calling it with the value you want to set:

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

Updated demo

I cannot find any available existing function to do what you want, but this seems to work nicely for me. Hope it is closer to the behaviour you require.

like image 29
andyb Avatar answered Sep 17 '22 13:09

andyb