Reputation: 2101
I set up a jquery autocomplete that queries an endpoint to get the choices in the input (once you start typing):
$("#brand-select").autocomplete({
source: function(request, response) {
$.getJSON(
'/networks?search='+request.term ,
function(data) {
data = JSON.parse(data);
response(data);
}
);
},
minLength: 1,
multiselect: true
});
Is there a way I can fill out the autocomplete so that there is text in the input right away (on page load)?
For example, after the autocomplete is set up, I want the input to automatically display 'ABC'
I know this isn't right but I've tried:
$("#brand-select").autocomplete(["ABC"]);
Upvotes: 2
Views: 1796
Reputation: 370
To achieve this, you just need a simple code to assign the element a conclusive value
then focus on it.
$('#brand-select').autocomplete({
lookup:function(request, response) {
$.getJSON(
'/networks?search='+request.term ,
function(data) {
data = data; // Data is already in JSON format
response(data);
}
);
},
minLength: 1,
multiselect: true
onSelect: function (suggestion) {
var name = suggestion.value;
}
});
Now set the value and focus on the element
$("#brand-select").val('ABC').focus();
// Ensure that ABC is available in the lookup / source
A conclusive value means that when autocomplete looks up or searches your source, it will get only one value.
Upvotes: 0
Reputation: 62060
Presumably brand-select
is an input box? Therefore you can inject the value directly (if you're using script to build your HTML) so you end up with something like <input type="text" id="brand-select" value="ABC"/>
.
Or you can just use standard jQuery to populate it, e.g. $("#brand-select").val("ABC");
.
The autocomplete relates to the dropdown and searching, but the input box underneath is unchanged, so you can treat it like any other input.
P.S. If you then want it to automatically perform a search based on that text, then call the autocomplete's "search()" method (see https://api.jqueryui.com/autocomplete/#method-search), e.g. $("#brand-select").autocomplete("search");
Upvotes: 0