Skip to content
Advertisement

Match any part of an autocomplete string, not only the first letters

I’d like to use this code from w3school for a custom autocomplete dropdown. Already installed on my website, it works very well. Only one thing I’d like to improve is have it match any part of string. For instance here (to take the example of w3school), if I type “Bel” in the text field, I’ll have “Belgium” as a result. I’d like to have “Belgium” shown as well if I type “gium”. Do you guys think it is possible? If so, how can I achieve this?

Thanks for your help! Have been struggling on this for the whole day.

Code is here (w3school “Try it yourself” tool)

Benjamin

Advertisement

Answer

You need to Change compare condition:

In current code it is check if the item starts with the same letters as the text field value

JavaScript

Here from the array of countries it get the country and do the substring to length of input value.

JavaScript

As per the requirement you have to check if country from array of countries include the input String value.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement