1

i am currently working with a js function that gives an html input field an autocomplete feature. This is working fine, however it only works for the first word a user gives. Is there a way to make the autocomplete function run for every word entered in a string?

here is the function

$(function() {
  $("#text-input").autocomplete({
    source: ["Eastern Redbud", "Eastern White Pine", "Eastern Red cedar",],
    minLength: 1

  });
});

TheMayerof
  • 183
  • 2
  • 4
  • 15

1 Answers1

0

Refering here the first answer you can use document.body.onkeyup and then check for the space with e.keyCode == 32

When Space was pressed then call your autocomplete function now you have to split your input field value at the spaces and take the last element to apply the autocomplete only to the new word.

document.body.onkeyup = function(e){
  // execute when space was pressed  
  if(e.keyCode == 32){
       
    // apply the autocomplete only at the first word in the input field
let inputWords = $("#text-input").split(" ");
inputWords[inputWords.length -1].autocomplete({
    source: ["Eastern Redbud", "Eastern White Pine", "Eastern Red cedar",],
    minLength: 1

  });
    }
}
Aalexander
  • 4,987
  • 3
  • 11
  • 34