0

I need a little help with jquery. I am trying to add link functionality to an auto complete list. Basically, it displays suggested links based on what is typed in the input. Below are the scripts that produce only the auto complete...

I am using a plugin (omitted from this post), but it can be viewed here if needed: https://www.cssscript.com/demo/autocomplete-typeahead-bootstrap-5/autocomplete.js

My code at the bottom of the HTML:

  <script>
    var datasrc = [
      {label: 'About', value: 'about.html'},
      {label: 'Components', value: 'components.html'},
      {label: 'Usage', value: 'usage.html'},
    ]
    const ac = new Autocomplete(document.getElementById('autosuggest'), {
      data: datasrc,
      treshold: 1,
      maximumItems: 8,
      onSelectItem: ({label, value}) => {
        console.log("user selected:", label, value);
      }
    });
  </script>

I ran into this post: JQuery Autocomplete Where the Results are Links - but I'm not sure how to integrate an "event function" into the above code.

jottin
  • 241
  • 1
  • 9
  • 2
    try adding **location.href = value;** to the onSelectItem and when the person selects that item, they will automatically be taken to that link. – imvain2 Jul 08 '22 at 19:57
  • 1
    I agree with @imvain2. You could also use window.open(value, '_blank'); if you want it to open in a new browser tab. – Poku Jul 08 '22 at 20:03
  • after adding (location.href = value;), it only appears to refresh the page and the url does not change to the value specified. – jottin Jul 11 '22 at 12:41
  • I believe this is because the output are buttons and not anchors. There is no href being generated which makes sense why the page only refreshes. – jottin Jul 11 '22 at 13:27

1 Answers1

0

While adding location.href = value; adds the functionality, it only refreshes the page. The plugin generates buttons. So, I changed the line in autocomplete.js which creates the item from this:

<button type="button" class="dropdown-item" data-value="${item.value}">${label}</button>

to this:

<a class="dropdown-item" href="${item.value}">${label}</a>

and now it produces clickable links!


UPDATE:

I forgot to mention that location.href = value; is not needed once the button output is changed to an anchor. If not removed, it could cause an undefined error after clicked.

Also, to refresh the page when an anchor with a hash tag is clicked (strange I know), I added the below code in autocomplete.js to reload the page with the hash tag intact. The autocomplete menu on mobile needed to reload the page due to another script preventing scrolling on the page body while the menu is active. Reloading the page resets the body.

location.href = e.target.href;
location.reload();
jottin
  • 241
  • 1
  • 9