Reputation: 1131
Given a straightforward jQuery Autocomplete, I'm trying to figure out how to dynamically add whatever the user has typed into the textbox as the first item that gets returned in the list.
$(document).ready(function() {
$("input#autocomplete").autocomplete({
source: ["Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliet", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo", "Sierra", "Tango", "Uniform", "Victor", "Whiskey", "X-ray", "Yankee", "Zulu"]
});
});
For instance, if the user types "Alph", the autocomplete will return:
With the "Alpha" coming from the autocomplete source and the "Alph" being dynamically inserted.
I appreciate any help as I am very new to jQuery and currently surfing the learning curve.
Upvotes: 0
Views: 639
Reputation: 1898
$(document).ready(function() {
$("input#autocomplete").autocomplete({
source: function(request, response){
var options = ["Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliet", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo", "Sierra", "Tango", "Uniform", "Victor", "Whiskey", "X-ray", "Yankee", "Zulu"];
var results = [request.term];
var regex = new RegExp(request.term, "i");
for(var i = 0; i< options.length; i++){
if (options[i].match(regex))
results.push(options[i]);
}
response(results);
}
});
});
Upvotes: 1
Reputation: 2376
I would try something like this:
var options = [request.term, "Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliet", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo", "Sierra", "Tango", "Uniform", "Victor", "Whiskey", "X-ray", "Yankee", "Zulu"];
function source_function(request, response) {
// make a new array with the dynamic term + all of your other options
var autoOptions = [request.term].concat[options];
/*
Your code to prune the options
*/
// function to pass the displayed options back to
response(options);
}
$(document).ready(function() {
$("input#autocomplete").autocomplete({
source: source_function
});
});
The best option overall is to use a dynamic function to specify constantly what appears in the auto complete menu.
Upvotes: 0