Question

I have a long, unordered list on a page. It looks something like this

<ul>
  <li>
    <a href="http://www.google.com">
      Google
    </a>
  </li>
  <li>
    <a href="http://www.yahoo.com">
      Yahoo
    </a>
  </li>
</ul>

Instead of displaying a list of links, I'd rather display it as a jQuery autocomplete where typing "Ya" will display the word "Yahoo" and when clicked (or after pressing "Enter") will take you to its href.

Is there any way I can get the contents of this dynamically changing list and display it instead as an autocomplete?

Was it helpful?

Solution

Assuming you are using jQuery UI,

Step 1 - Add an text input for your autocomplete:

<input type="text" id="search" />

Step 2 - Convert your DOM to a list of links:

var items = [];

$('ul li a').each(function () {
    items.push({ 
        value: $(this).attr('href'),
        label: $(this).text()
    });
});

$('ul').remove();

Step 3 - Turn on the autocomplete:

$("#search").autocomplete({
    source: items,
    select: function (event, ui) { 
        window.location.href = ui.item.value;
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top