0

What I'm trying to do is use jquery autocomplete and display the title if matches title or keywords This is the code I have but I can't get it to work the way I need it to, I have been able to make it search title if i throw it in a regular array but not title and keywords. Any help would be excellent, thanks in advance.

var VideoNames = [{title: "superman", keywords: "super man hero movie"}]

$("#searchbox").autocomplete({
    source: VideoNames,
    select: function (event, ui) {
        $("#searchbox").val(ui.item.value);
        TrainingVideos.search(ui.item.value);
    }
});

1 Answer 1

1

To achieve such result you should use function variation of source property of autocomplete's settings object. The function will be called each time input's value changes. Therefore you need to return an array of matched titles. To do so create a new RegExp object with request term as pattern. Then using the RegExp object match both title and keywords of items of the original array. Lastly map them to show just titles. Here is the result:

const videos = [
  {
    title: "superman",
    keywords: "super man hero movie"
  },
  {
    title: "batman",
    keywords: "batmobile driving guy"
  },
  {
    title: "captain america",
    keywords: "hero star us"
  }
]

$("#searchbox").autocomplete({
  source (request, response) {
    const matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i")
    
    response(
      videos
        .filter(item => matcher.test(item.title + item.keywords))
        .map(item => item.title)
    )
  }
});
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>

<input id="searchbox">

Sign up to request clarification or add additional context in comments.

3 Comments

I wish I could give you more rep then just one! But thank you very much!
@Tony You're welcome. :) Also you can accept the answer.
Thanks again, I just did

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.