Autocomplete Middle Of The Text Not Only On Start
Is there a way to implement a custom autocomplete list in middle of the text not just from the beginning? Lets say, I have a custom autocomplete list like this. ['@Martin','@Josu',
Solution 1:
const searchInput = document.getElementById("search");
const output = document.getElementById("output");
const names = [
"@Martin",
"@Josu",
"@Mikenko",
"@Buarandun",
"@Ravindran",
"Basix",
"#ItemNr"
];
searchInput.addEventListener("input", matchNames);
functionmatchNames(e) {
const { value } = e.target;
output.innerHTML = ""// start matching if '@' symbol foundif (value.includes("@")) {
const symbolIndex = value.indexOf("@"); // get the symbol indexconst matchValue = value.substring(symbolIndex); // start matching from symbol indexconst matchList = names.filter(
name => name.toLowerCase().indexOf(matchValue.toLowerCase()) !== -1
);
// outputconst html = matchList.map(name => {
constName = name
.toLowerCase()
.replace(matchValue, `<strong>${matchValue}</strong>`)
return`<span class="name">${Name}</span>`
}).join("")
// push data into output
output.innerHTML = html
}
}
.name {
display: block
}
<inputid="search"type="text"class="form-control"placeholder="names"><divid="output"></div>
Solution 2:
This part
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
convert to
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
val = val.split(' ').reverse()[0]; // Get last
This should get last word always
Solution 3:
you can apply condition based on characters length after which you want to start autocomplete. For example you can say
if(yourInput.length > 3 ) {
//your rest autocomplete thing here
}
Solution 4:
You can use search()
method. Read about it here.
Change following
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
to
if (val.toUpperCase().search(arr[i].toUpperCase()) != -1) {
Not tested, Hope this helpful :)
Solution 5:
You just need to change
var a, b, i, val = this.value.split("@");
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val || val.length < 2) { returnfalse;}
val = val[val.length-1]
then
if(arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase())
to
if(arr[i].toLowerCase().indexOf(val.toLowerCase()) !== -1)
And change showing the list from
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
to
b.innerHTML = arr[i].toLowerCase().replace(val.toLowerCase(), '<b>' + val.toLowerCase() + '</b>');b.style.textTransform = "capitalize";
It will start to show autocomplete when you just typed '@' in your text.
Example codepen
Post a Comment for "Autocomplete Middle Of The Text Not Only On Start"