0

I would like the user to fill in several words in a free text field. These words must form a autocomplete list that has its source from an external text file. And also: if no suggestion is found, the typed in text is also accepted.

I got it working when you start typing a word, but if the second word that is typed is not exactly matching the value of the item in the text file, it does not get returned in the suggestion list...

How do I do this? This is what I have.

I have an input field:

<input type="text" id="Textbox_6175_1">

Then a have the script:

<script>
$.ajax({
    url: "path-to-file.txt",
    dataType: "text",
    success: function(data) {
        var autoCompleteData = data.split('\n');
        $("#Textbox_6175_1").autocomplete({
            source: function(request, response) {
                var results = $.ui.autocomplete.filter(autoCompleteData, request.term);
                response(results.slice(0, 20));
            }
        });
    }
});
</script>

And I have the external text file with values like:

Elton John - Blue Eyes
Elton John - Border Song
Elton John - Can You Feel The Love Tonight
Elton John - Candle In The Wind 1997
Elton John - Circle Of Life
Elton John - Club At The End Of The Street
Elton John - Crocodile Rock
Elton John - Cry To Heaven
Elton John - Daniel
Elton John - Don't Let The Sun Go Down On Me
Elton John - Goodbye Yellow Brick Road
Elton John - I'm Still Standing
Elton John - Nikita
Elton John - Nobody Wins
Elton John - Sacrifice
Elton John - Someone Saved My Life Tonight
Elton John - Something About The Way You Look Tonight
Elton John - Song For Guy
Elton John - Sorry Seems To Be The Hardest Word
Elton John - The Bitch Is Back
Elton John - The Last Song
Elton John - The One
Elton John - You Gotta Love Someone
Elton John - Your Song
Elvis Presley - (Now And Then There's) A Fool Such As I
Elvis Presley - (Such An) Easy Question
Elvis Presley - All Shook Up
Elvis Presley - Always On My Mind
Elvis Presley - Are You Lonesome Tonight (Laughing Version)
Elvis Presley - Burning Love
Elvis Presley - Crying In The Chapel
Elvis Presley - Do The Clam
Elvis Presley - Don't Cry Daddy
Elvis Presley - I Just Can't Help Believin'
Elvis Presley - In The Ghetto
Elvis Presley - Jailhouse Rock
Elvis Presley - Love Letters
Elvis Presley - Moody Blue
Elvis Presley - My Boy
Elvis Presley - My Way
Elvis Presley - One Night
Elvis Presley - Rubberneckin' (Paul Oakenfold Remix Radio Edit)
Elvis Presley - Stay Away
Elvis Presley - Suspicious Minds
Elvis Presley - Suspicious Minds (1999)
Elvis Presley - U.S. Male
Elvis Presley - Way Down
Elvis Presley - Wooden Heart (Muss I Denn...)
Elvis Presley & JXL - A Little Less Conversation

This results in a nice max. 20 line suggestion box... but ONLY when I type in values that are next to each other, matching the values in the text file.

I would like the user, when he types the two words 'el can' to see a suggestion box with:

Elvis Presley - I Just Can't Help Believin'
Elton John - Can You Feel The Love Tonight

Someone any idea's??

  • Would advise performing the AJAX call from the Source of the Autocomplete instead of initializing the Autocomplete in the Ajax. See: https://api.jqueryui.com/autocomplete/#option-source – Twisty Jun 22 '23 at 18:36

1 Answers1

0

To address this, you have two issues to overcome. Consider this first:

https://jsfiddle.net/Twisty/ok3945ba/12/

JavaScript

$(function() {
  var myText = "Elton John - Blue Eyes,Elton John - Border Song,Elton John - Can You Feel The Love Tonight,Elton John - Candle In The Wind 1997,Elton John - Circle Of Life,Elton John - Club At The End Of The Street,Elton John - Crocodile Rock,Elton John - Cry To Heaven,Elton John - Daniel,Elton John - Don't Let The Sun Go Down On Me,Elton John - Goodbye Yellow Brick Road,Elton John - I'm Still Standing,Elton John - Nikita,Elton John - Nobody Wins,Elton John - Sacrifice,Elton John - Someone Saved My Life Tonight,Elton John - Something About The Way You Look Tonight,Elton John - Song For Guy,Elton John - Sorry Seems To Be The Hardest Word,Elton John - The Bitch Is Back,Elton John - The Last Song,Elton John - The One,Elton John - You Gotta Love Someone,Elton John - Your Song,Elvis Presley - (Now And Then There's) A Fool Such As I,Elvis Presley - (Such An) Easy Question,Elvis Presley - All Shook Up,Elvis Presley - Always On My Mind,Elvis Presley - Are You Lonesome Tonight (Laughing Version),Elvis Presley - Burning Love,Elvis Presley - Crying In The Chapel,Elvis Presley - Do The Clam,Elvis Presley - Don't Cry Daddy,Elvis Presley - I Just Can't Help Believin',Elvis Presley - In The Ghetto,Elvis Presley - Jailhouse Rock,Elvis Presley - Love Letters,Elvis Presley - Moody Blue,Elvis Presley - My Boy,Elvis Presley - My Way,Elvis Presley - One Night,Elvis Presley - Rubberneckin' (Paul Oakenfold Remix Radio Edit),Elvis Presley - Stay Away,Elvis Presley - Suspicious Minds,Elvis Presley - Suspicious Minds (1999),Elvis Presley - U.S. Male,Elvis Presley - Way Down,Elvis Presley - Wooden Heart (Muss I Denn...),Elvis Presley & JXL - A Little Less Conversation";

  $("#Textbox_6175_1").autocomplete({
    source: function(request, response) {
      $.post("/echo/html/", {
        html: myText
      }, function(results) {
        results = $.ui.autocomplete.filter(results.split(","), request.term);
        if (results.length > 20) {
          results = results.slice(0, 20);
        }
        response(results);
      });
    }
  });
});

Your data source, the Text file, I am assuming cannot be modified. So you will need to use $.get() or $.ajax() to read the Text file and split it with \r\n. What you see here is just for this example, yet it gives yo ua working test.

In the end, you will have an array of items.

With the above example, when you search:

  • "el" - you will get 20 results
  • "el " - you get one results
  • "el can" - you get zero results

This is the crux of your second hurdle. You need a more complex filter to find "el" AND "can" in the dataset.

Consider the following:

https://jsfiddle.net/Twisty/ok3945ba/25/

JavaScript

$(function() {
  var myText = "Elton John - Blue Eyes,Elton John - Border Song,Elton John - Can You Feel The Love Tonight,Elton John - Candle In The Wind 1997,Elton John - Circle Of Life,Elton John - Club At The End Of The Street,Elton John - Crocodile Rock,Elton John - Cry To Heaven,Elton John - Daniel,Elton John - Don't Let The Sun Go Down On Me,Elton John - Goodbye Yellow Brick Road,Elton John - I'm Still Standing,Elton John - Nikita,Elton John - Nobody Wins,Elton John - Sacrifice,Elton John - Someone Saved My Life Tonight,Elton John - Something About The Way You Look Tonight,Elton John - Song For Guy,Elton John - Sorry Seems To Be The Hardest Word,Elton John - The Bitch Is Back,Elton John - The Last Song,Elton John - The One,Elton John - You Gotta Love Someone,Elton John - Your Song,Elvis Presley - (Now And Then There's) A Fool Such As I,Elvis Presley - (Such An) Easy Question,Elvis Presley - All Shook Up,Elvis Presley - Always On My Mind,Elvis Presley - Are You Lonesome Tonight (Laughing Version),Elvis Presley - Burning Love,Elvis Presley - Crying In The Chapel,Elvis Presley - Do The Clam,Elvis Presley - Don't Cry Daddy,Elvis Presley - I Just Can't Help Believin',Elvis Presley - In The Ghetto,Elvis Presley - Jailhouse Rock,Elvis Presley - Love Letters,Elvis Presley - Moody Blue,Elvis Presley - My Boy,Elvis Presley - My Way,Elvis Presley - One Night,Elvis Presley - Rubberneckin' (Paul Oakenfold Remix Radio Edit),Elvis Presley - Stay Away,Elvis Presley - Suspicious Minds,Elvis Presley - Suspicious Minds (1999),Elvis Presley - U.S. Male,Elvis Presley - Way Down,Elvis Presley - Wooden Heart (Muss I Denn...),Elvis Presley & JXL - A Little Less Conversation";

  $("#Textbox_6175_1").autocomplete({
    source: function(request, response) {
      $.post("/echo/html/", {
        html: myText
      }, function(results) {
        var myData = results.split(",");
        var terms = request.term.split(" ");
        var myResults;
        if (terms.length == 1) {
          myResults = $.ui.autocomplete.filter(myData, terms[0]);
        } else {
          myResults = myData.filter(s => terms.some(w => s.includes(w)));
        }
        if (myResults.length > 20) {
          myResults = myResults.slice(0, 20);
        }
        response(myResults);
      });
    }
  });
});

Reference: Javascript search multiple word in array

Now you should be getting the results you are expecting when searching for "el can"

Update

Found a good example that uses Regular Expressions: https://stackoverflow.com/a/37692545/463319

Per the following, we now get expected results:

https://jsfiddle.net/Twisty/ok3945ba/43/

JavaScript

$(function() {
  var myText = "Elton John - Blue Eyes,Elton John - Border Song,Elton John - Can You Feel The Love Tonight,Elton John - Candle In The Wind 1997,Elton John - Circle Of Life,Elton John - Club At The End Of The Street,Elton John - Crocodile Rock,Elton John - Cry To Heaven,Elton John - Daniel,Elton John - Don't Let The Sun Go Down On Me,Elton John - Goodbye Yellow Brick Road,Elton John - I'm Still Standing,Elton John - Nikita,Elton John - Nobody Wins,Elton John - Sacrifice,Elton John - Someone Saved My Life Tonight,Elton John - Something About The Way You Look Tonight,Elton John - Song For Guy,Elton John - Sorry Seems To Be The Hardest Word,Elton John - The Bitch Is Back,Elton John - The Last Song,Elton John - The One,Elton John - You Gotta Love Someone,Elton John - Your Song,Elvis Presley - (Now And Then There's) A Fool Such As I,Elvis Presley - (Such An) Easy Question,Elvis Presley - All Shook Up,Elvis Presley - Always On My Mind,Elvis Presley - Are You Lonesome Tonight (Laughing Version),Elvis Presley - Burning Love,Elvis Presley - Crying In The Chapel,Elvis Presley - Do The Clam,Elvis Presley - Don't Cry Daddy,Elvis Presley - I Just Can't Help Believin',Elvis Presley - In The Ghetto,Elvis Presley - Jailhouse Rock,Elvis Presley - Love Letters,Elvis Presley - Moody Blue,Elvis Presley - My Boy,Elvis Presley - My Way,Elvis Presley - One Night,Elvis Presley - Rubberneckin' (Paul Oakenfold Remix Radio Edit),Elvis Presley - Stay Away,Elvis Presley - Suspicious Minds,Elvis Presley - Suspicious Minds (1999),Elvis Presley - U.S. Male,Elvis Presley - Way Down,Elvis Presley - Wooden Heart (Muss I Denn...),Elvis Presley & JXL - A Little Less Conversation";

  // Ref: https://stackoverflow.com/questions/3041320/regex-and-operator
  function fullTextCompare(myWords, toMatch) {
    //Replace regex reserved characters
    myWords = myWords.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    //Split your string at spaces
    var arrWords = myWords.split(" ");
    //Encapsulate your words inside regex groups
    arrWords = arrWords.map(function(n) {
      return ["(?=.*" + n + ")"];
    });
    //Create a regex pattern
    sRegex = new RegExp(arrWords.join("") + ".*", "im");
    //Execute the regex match
    return (toMatch.match(sRegex) === null ? false : true);
  }

  $("#Textbox_6175_1").autocomplete({
    source: function(request, response) {
      $.post("/echo/html/", {
        html: myText
      }, function(results) {
        var myData = results.split(",");
        var myResults;
        if (request.term.indexOf(" ") == -1) {
          myResults = $.ui.autocomplete.filter(myData, request.term);
        } else {
          myResults = [];
          $.each(myData, function(j, title) {
            if (fullTextCompare(request.term, title)) {
              myResults.push(title);
            }
          });
          myResults.sort();
          console.log(request.term, results);
        }
        if (myResults.length > 20) {
          myResults = myResults.slice(0, 20);
        }
        response(myResults);
      });
    }
  });
});

Update 2, for TXT File

$(function() {
  var textFile = "path-to-file.txt";

  function fullTextCompare(myWords, toMatch) {
    myWords = myWords.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    var arrWords = myWords.split(" ");
    arrWords = arrWords.map(function(n) {
      return ["(?=.*" + n + ")"];
    });
    sRegex = new RegExp(arrWords.join("") + ".*", "im");
    return (toMatch.match(sRegex) === null ? false : true);
  }

  $("#Textbox_6175_1").autocomplete({
    source: function(request, response) {
      $.get(textFile, function(results) {
        var myData = results.split("\r\n");
        var myResults;
        if (request.term.indexOf(" ") == -1) {
          myResults = $.ui.autocomplete.filter(myData, request.term);
        } else {
          myResults = [];
          $.each(myData, function(j, title) {
            if (fullTextCompare(request.term, title)) {
              myResults.push(title);
            }
          });
          myResults.sort();
          console.log(request.term, results);
        }
        if (myResults.length > 20) {
          myResults = myResults.slice(0, 20);
        }
        response(myResults);
      });
    }
  });
});
Twisty
  • 30,304
  • 2
  • 26
  • 45
  • When trying out your https://jsfiddle.net/Twisty/ok3945ba/25/ I do not seem to get any result on 'Elvis always'. One should expect to see 'Elvis Presley - Always On My Mind' as a suggestion. Also, when typing 'el can', it gives me 5 suggestions of which 2 are correct :) – Keston Pollard Jun 22 '23 at 22:55
  • Also: I have many thousands of suggestions in that text file, so I'd rather not create it into an array. – Keston Pollard Jun 22 '23 at 23:13
  • @KestonPollard when you perform `.split('\n')`, this turns it into an Array already, so I am a bit confused by your statement. – Twisty Jun 22 '23 at 23:22
  • True, It's because I'm a novice... what do you think about my first comment, though? – Keston Pollard Jun 23 '23 at 06:42
  • @KestonPollard I have been looking at it and working on it. Since you are trying to find a phrase based on multiple words, it is more complex and there are a number of ways to accomplish that. I have been trying multiple alternatives. I might switch it to a Regular Expression search, something like `elvis|always`. – Twisty Jun 23 '23 at 19:07
  • @KestonPollard updated answer, it is now hitting multiple words properly. – Twisty Jun 23 '23 at 19:33
  • YES, That works great! What do I need to change in order to use the txt file? For me this has to be the case because of multiple people working on the same file (the text file). – Keston Pollard Jun 24 '23 at 03:53
  • 1
    @KestonPollard see second update. – Twisty Jun 26 '23 at 15:55