pixabay / javascript-autocomplete Goto Github PK
View Code? Open in Web Editor NEWAn extremely lightweight and powerful vanilla JavaScript completion suggester.
An extremely lightweight and powerful vanilla JavaScript completion suggester.
This a great lightweight plugin! A question rather than a bug... like in a select form field with options, the value can be different to the selected text. E.g. you might have an integer ID for something and a string to describe what it is. Is there an easy way I can implement something similar with this plugin or will I have to use a lookup with the onSelect()
callback? Thanks
Since the point of this project is to not need jquery, it seems odd to only include ajax examples that require jquery. I'd love to not have to learn enough about jquery to not need it for doing ajax. Reference: https://blog.garstasio.com/you-dont-need-jquery/ajax/
Thanks!
Would be great to have an option that would auto-select the first result so you don't have to hit down or use the mouse and can just hit Enter
(or Tab
). I'd also populate the input box with the result by default maybe.
I get this error:
Uncaught NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
in my console after I begin removing characters from my searchbar field. This is my 'destroy' function:
("#searchBar").on('input', function(event){
my_autoComplete.destroy();
});
Afterwards, the message just shows up after any key press.
Your how-to documentation really requires the HTML that must accompany your Javascript. It isn't yet clear to me how to a) pass in the term, b) receive results in the callback, or c) use a returned div.
The problem happen when i try to use this plugin with pop-up or modal in another plugin but when i do that the position of autocomplete is very wrong.
https://goodies.pixabay.com/javascript/auto-complete/demo.html
type "sca"
expected: Scala
actual: 14 results: ActionScript, AppleScript, Asp ..... Scala, Scheme, SQL
mousedown event on element
.autocomplete-suggestion
propagates back to input field which triggers focus.
live('autocomplete-suggestion', 'mousedown', function(e){ if (hasClass(this, 'autocomplete-suggestion')) { // else outside click var v = this.getAttribute('data-val'); that.value = v; o.onSelect(e, v, this); that.sc.style.display = 'none'; } }, that.sc);
On focus the below event is triggered, because of which .autocomplete-suggestion is again visible.
if (!o.minChars) addEvent(that, 'focus', that.focusHandler);
To avoid this I have added e.preventDefault();
in live('autocomplete-suggestion', 'mousedown', function(e){...}
function.
Please see if you can recreate and provide a better solution for this.
I just found out autoComplete doesn't work when i have multiple search fields on my page using the same "selector" option key.
I would expect to see a suggestion list below the search field i type in. But what actually happens that it only shows the last suggestion list created. This is because because the reference of the "that" variable is assigned to the last element because of the for loop.
The temporary fix i apllied is to build two autoComplete instances with both using the same options
Hopefully this can me be fixed in a future version
Currently, with cache: true
, the library will use its cache also for other query strings that are subsets of the user's query. However, this doesn't work for all use-cases. For example, I have an autocomplete field where the server uses the query as an ID to look up a row in the database. Thus, the results from a query like 1022
cannot be re-used to find results for 10228
. It would be great if there was a way to specify that the cache must be exact (i.e., that the cache should only be used for lookups, not for searching).
Is it possible to use this on let's say a textarea? so like create a dropdown inside a textarea.
Kinda like here on GitHub when you mention someone?
o(∩_∩)o Hello.
I found this problem when after I selected one opinion by mouse click, the dropdownlist would immediately show again.
However,if I selected the opinion by keyboard enter, it doesn't have this problem.
(target input still own FOCUS, but the former keep shown dropdownlist but the latter didn't. )
Then I compare the javascript logic between keydownHandler and mousedown ,
the former to close the dropdownlist by use: setTimeout(function(){ that.sc.style.display = 'none'; }, 20);
the latter to close the dropdownlist by use: that.sc.style.display = 'none';
So, I tried to modify the code to setTimeout(function(){ that.sc.style.display = 'none'; }, 200);
in the mousedown handler , the problem I found would gone :)
BTW, as you notice ,Mmm....
I use 200ms instead of 20ms, because I was not sure why 20ms cannot fixed this issue but 200ms okay in mouse event. Does anybody have idea here?
Thanks so much :)
const autoComplete = require('javascript-autocomplete')
works nicely.
It would be nice to use newer syntax, something like import { autoComplete } from 'javascript-autocomplete'
.
A hackish solution would be something like this.
module.js:
const autoComplete = require('auto-complete');
export default autoComplete;
my-app.js:
import { autoComplete } from 'javascript-autocomplete/module'
I'm not sure the impact of that setup on bundlers like webpack. But seems like it should be at least functional.
Hi. I've noticed that this code breaks plugin.
renderItem: (item, term) => {
return `
<div class="autocomplete-suggestion" data-val="${term}">
${item.name}
</div>
`;
}
In this case after resolving next = (key == 40) ? sel.nextSibling : sel.previousSibling;
in lib code - next
will be equal to #text
node instead of DOM-node
.
And you'll see n.getAttribute is not a function
error.
To deal with it, you should write your code without new line after first `.
renderItem: (item, term) => {
return `<div class="autocomplete-suggestion" data-val="${term}">
${item.name}
</div>`;
}
Meh... Spent couple of hours to find it.
I have select item,and input has display value.
But I can't get value in angularjs controller.
The keyup and keydown events are not working on Mozilla Firefox browser for Android.
Hello
Would it be possible to have the suggester stop copying to the input field ONLY the last chosen item?
Ideally a developer might want any number of selected items to be placed in the field. Look at what I am doing here:
new autoComplete({
selector: tags[0],
minChars: 2,
cache: false,
source: function(term, suggest) {
term = term.toLowerCase();
console.log(term);
var bits = term.trim().split(/\s+/);
term = bits[bits.length - 1];
var choices = ['ActionScript', 'AppleScript', 'Asp', 'Java', "JavaScript", "php", "ruby"];
var matches = [];
for (var i = 0; i < choices.length; i++) {
if (~choices[i].toLowerCase().indexOf(term)) {
matches.push(choices[i]);
}
}
suggest(matches);
}
});
As you can see I am always taking the last word in the input as a query:
var bits = term.trim().split(/\s+/);
term = bits[bits.length - 1];
and of course I would like any subsequent choice to be appended to the input. At moment only the last choice is displayed (and any previous choice is deleted).
At the very least, when onSelect
is specified by the devloper, the library should stop firing its own onSelect
(which I believe it is what substitutes whatever is in the input field with the last choice made by the user).
would it be possible to have out there in the next release?
Thanks
Hi there,
I hope you shall be fine. I am using this autocomplete plugin for my project and is very helpful. Thank you for making it.
I am facing one issue though. I want to dynamically change the values in the choices array. How can I do that. If you look at the screenshots attached. I am using the autocomplete feature in the 2nd field. And the results in this field come on the basis of the choice selected in the first dropdown field. So I want to change the suggestions inside the 2nd field based on the value selected in the first dropdown field.
I am trying but I am unable to reset the choices array. Can you help me with that ?
I am using the method of searching in the local data. So I am setting "choices = choicesArray". The values in the choicesArray change dynamically but the choices array of your code remains the same. Kindly let me know of the solution.
When you have autocomplete working with multiple elements on beginning search results from xhttp over slow network, the autocomplete becomes visible when result is retrieved from server even when element is no longer active / in focus.
unable to select unique result from keyboard up and down chars.
I have some events/triggers that run on the onSelect()
to populate hidden fields. However, when the user goes to make a selection using the keyboard from the auto-complete then tabs away from the field, the onSelect() is not triggered. Is there any way of capturing a tab away as part of the onSelect()
function if the value has changed?
Line 57 "that.setAttribute('data-sc', that.sc);" is throwing a Unspecified error in IE10.
As far as I can see this code isn't used anywhere else so removing this line fixes the issue
I'm working on a search field with multiple suggestion sources that load at different times. Currently, I just append to the choices
array (used by the source
function) and delete the cache whenever a new source's JSON has loaded. This has been working great, with the exception that the new suggestions aren't visible until the user types or deletes a letter.
Is there any way to programmatically trigger a re-matching and re-rendering of suggestions? I've tried removing lastVal
and manually calling keyupHandler
and keydownHandler
but haven't had any luck. Thanks!
live('autocomplete-suggestion', 'mouseleave',
function(e){
var sel = that.sc.querySelector('.autocomplete-suggestion.selected');
if (sel) setTimeout(function(){ sel.className = sel.className.replace('selected', ''); }, 20);
}, that.sc);
What does this code mean?
I think it doesn't working.
Because that.sc and parent are not included "autocomplete-suggestion"
What do you think about it?
hi,
I solved the problem of double click on Apple (touch hover) by adding these events.
live('autocomplete-suggestion', 'touchstart', function(e){ is_scrolling = false; }, that.sc); live('autocomplete-suggestion', 'touchmove', function(e){ is_scrolling = true; }, that.sc); live('autocomplete-suggestion', 'touchend', function(e){ if(!is_scrolling){ var v = this.getAttribute('data-val'); that.value = v; o.onSelect(e, v, this); } }, that.sc);
After setup the script and show the results we need to click the search post button to complete the action, but i would like to on the suggestion submit the form without need to select. is that possible with the onSelect callback?
It adds every time that you move the cursor in the autocomplete menu more and more spaces in the class name attribute
Basically this is the solution:
Change all the 'selected' texts to ' selected' (a space after the first quote).
I attach the file with the modification
auto-complete.js.zip
and the diff.
auto-complete.js.diff.zip
This is a enhancement request if that's OK:
So far this is the best vanilla JS autocomplete library I've been able to find, but it's obviously designed to only work on inputs. It would be, simply outstanding, if it could be modified to accept textarea
's and listen for triggers like @
to make mentioning possible.
For my project doing such a thing in vanilla JS is a requirement and I'm in the process of writing a helper class on top of this project to make it work, but it's proving difficult.
Ok. I have an issue that i cant figure it out :(
My problem is that i use special characters in my language. What i mean is that in Greek Language the letters α, ά or ε, έ are the same letters but if you type the letter α in the search input field it doesn't highlight also the letters ά in the results list ! How can i force the plugin return results for both "α, ά" when i type "α" in the search input field and vice versa when i type "ά" to return both "α, ά" ??
This is very important in Greek Language or other non-latin languages like cyrillic etc.
Thanks!
This autocomplete script is fantastic, thank you for making it publicly available!
However, for my use case, I need it to display the options every time space is pressed. So let's say, for the sake of simplicity, I have a local suggestion array with "sale price" and "item cost", and I already typed in "how much is my" in the input textbox, is there a way to show those two options when I press space, only "sale price" when I then press 's', then fill in "sale price" at the end of the text (rather than replacing all of it) when I select that option?
Thank you
I am getting an error as below:
TypeError: item.replace is not a function auto-complete.js:44:90
in this context
return '
It because my function returns array of elements like {tag:'name', description:'description'} instead of plain strings. Is it possible to wrap an element of an array processing to function like
extractString(element)
if an element is already a string just return it, otherwise get field specified in settings.
It is just a suggestion.
Hi ladies and gents,
This is my situation:
var choices = ['ActionScript', 'AppleScript', 'Asp'];
Above is my data object for autoComplete suggestions, however, I wanted to be able to nest more data within those items (in my case to prevent a second request after selecting an item), so that as soon as the user selects the item, there is already some data to display.
So basically, I would like to render it as such:
return '<div data-json="' + item.data + '" data-text="' + item + '"></div>'
where as my data source would look something like json:
var choices = [{name: 'foo', data 'bar'}, 'AppleScript', 'Asp'];
Thus once selected, in the callback I am able to get the dataAttribute('data-json')
, and render a different list without having to wait for another request to the server.
If anyone has any advice, it is greatly appreciated.
It would be very useful to have this as an npm-package. It is as easy as adding a package.json
to the project.
when keyboard up or down button pressed, the focus change of 2 instead of 1.
edit: my miss sorry (double init)
Anyone can suggest me, please?
The autocomplete drop down doesn't display at all on firefox
Is there an option to turn off caching? It's a nice feature but I am currently filtering options in the list based on other elements which means that it doesn't aways show the correct options.
EDIT: I found the options - my bad
bower install javascript-auto-complete
results in Package javascript-auto-complete not found.
I see there's a bower.json
config but has this module been registered? http://bower.io/docs/creating-packages/
If so, perhaps the lack of semver version tags means it can’t be found.
Hi,
Someone has a code example using this plugin with ajax but without jquery?.
For me, that could be great! because in my case my project doesn't have jquery and on the website, there are only examples using jquery.
When you select a text that contains quotes, only the part before the quote is inserted in the textbox.
Example text:
This is "text" with quotes
After selecting the value, only the following text will be in the textbox
This is
This issue should be fixed in the renderItem function:
function (item, search)
{
// escape special characters
search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi");
return '<div class="autocomplete-suggestion" data-val="' + item + '">' + item.replace(re, "<b>$1</b>") + '</div>';
}
Change this code:
'<div class="autocomplete-suggestion" data-val="' + item + '">'
To this code:
'<div class="autocomplete-suggestion" data-val="' + item.replace(/"/g, '"') + '">'
It would be great if we could to add custom elements at the end of generated items.
For example:
<div class="autocomplete-suggestions suggestions">
<div class="autocomplete-suggestion" data-val="iphone 7">iphone 7</div>
<div class="autocomplete-suggestion" data-val="iphone 6">iphone 6</div>
<div class="autocomplete-suggestion" data-val="iphone 5s">iphone 5s</div>
<div class="autocomplete-suggestion" data-val="iphone se">iphone se</div>
<div class="autocomplete-suggestion" data-val="iphone">iphone</div>
<div class="my-custom-permanent-element">Press Enter to search</div>
</div>
I want to use my-custom-permanent-element
- as help text.
So I think we need ability to add custom non-interactive items or we need a callback, that will be fired after list items rendering.
Thanks!
Is it possible to change the width of the suggestion list?
See here: https://codepen.io/anon/pen/vdMdxB
If you start to type "Aus" then I want to see the full value:
I see that the width is same as the input text field width: https://github.com/Pixabay/JavaScript-autoComplete/blob/master/auto-complete.js#L68
Is there any specific reason for that? ( how can I overwrite that? )
This is unexpected behaviour and should probably be avoided by default.
For any who are looking to avoid the form submitting, it's just a matter of preventing the default action of the event, and it can be done in onSelect
:
var ac = new autoComplete({
...
onSelect: function (event, term, item) {
event.preventDefault();
...
},
});
When currently installed through Bower it will use the wildcard version, which is not ideal. Can you create proper tags for the versions so that we can lock those down properly?
Hey,
Is it possible to load the result into a specific element?
Currently the list (autocomplete-suggestion) is appended to the body.
First congratulation about this very nice and effective piece of code and leting it open to others!
I have it integrated on my on going RLITE project, which goal is to facilitate embedding structured data and report it with text, all into a web site...
I used your code for what I name "Filtre", see, arrond line 120 (code will change a bit...) It was very straightforward to integrate!!!
Just one small improvement, could you add an option 'reselect', which would trigger the last suggested item list popup when you click in an input that was used as the last suggestion, choice being 'completed' or not.
Like this, in my use case, the user can select as an exemple, a customer (with the contact name), then select the associated Orders with an other suggestion input, click on a refresh button, which would then go and fetch the corresponding order detail. Then when she/he clicks back on the order suggestion input, she/he has the choice of selecting a new order to select and see it...Much easier than erase and retype the input...
What do you think?
Thanks a lot again! Very nice job!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.