I am using the jquery autocomplete plugin, and am trying to trigger the autocomplete manually based on certain keys the user enters. I'm trying to bind the autocomplete to the input on the fly so the autocomplete can start looking for matches once a user enters a certain key to trigger "I'm now entering data to be searched on", which could be in the middle of the field, not necessarily at the beginning.
I'm binding a keypress event to an input. When the user enters a certain key, like "=", I want to display all of the elements in the array. When the user then enters a letter it would autocomplete the options that match from the array for that character on. This is more or less trying to mimic what happens in Excel, when a user hits the equals key and sees the functions available, except the "=" key does not have to be the first element in the input, it should autocomplete every time "=" is pressed and unbind that ac every time an option is selected.
var array1 = ['one','two','three'];
$.input1.bind('keypress', function(event) {
var keyCode;
if (event.keyCode > 0) {
keyCode = event.keyCode;
} else if (typeof(event.charCode) != "undefined") {
keyCode = event.charCode;
}
if (String.fromCharCode(keyCode) == '=') {
$.input1.unbind('keypress');
$.input1.autocomplete(array1);
$.input1.blur();
$.input1.focus();
e = $.Event('keydown');
e.which = keyCode;
$.input1.trigger(e);
}
});
Even if I get the autocomplete to trigger, if the user has entered anything before the text that might match, it wouldn't match because of the previous text. So, if the user enters "abd =", the autocomplete is getting "abb =" as its q parameter and not just "=".
Any help is really appreciated, im so stuck!!
What you really need is to be able to filter the value of the field before the autocomplete plugin does the searching. Looking at the plugin it doesn't look like that is built in. BUT that doesn't stop us from adding it.
Open up the plugin code and find the function lastWord(), look at line 261. Then add this to that function:
So the lastWord function should look like:
Then in your jquery code you can do something like this:
This will let you filter and format the value of the field before the search. Since you only want to do the search if the value has the "=" character in it you search for it and if its not found you return an empty string. If its found you remove it and everything before it and return what the user is typing in after it.
You can modify your autocomplete.js by adding the second line of code
Then you refer to keydownEvent inside your sorce function like this
Remember that the var event has a which field. For example if event.which is 13 then the key Enter was pressed. Hope it helps.