user2386341
user2386341

Reputation: 25

Utilizing Bootstrap's typeahead as a search function

I've got typeahead working just fine, but I am too inexperienced with the Javascript to understand how to turn the typed results into a link.

<input type="text"
                       class="span3"
                       data-provide="typeahead"
                       placeholder="City Search:"
                       data-items="6"
                       autocomplete="off" 
                       data-source=[&quot;Neuchatel&quot;,&quot;Moutier&quot;]">

So, I really just want to know how to turn the strings from data-source into links to other pages. Hopefully this is fairly simple.

thanks!

Upvotes: 2

Views: 5946

Answers (1)

Carol Skelly
Carol Skelly

Reputation: 362360

You can turn the strings into links easily..

<input type="text" data-provide="typeahead" data-source="[&quot;/foo.html&quot;,&quot;http://www.google.com&quot;,&quot;/about.html&quot;]">

Are you also looking to take the link from the input and then navigate to the selected page?

EDIT: Navigate to item selected in typeahead..

In this case you'd define an object map that contain keys (label) and values (url) like..

var data = {
  "login":"/login",
  "home":"/",
  "user":"/user",
  "tags":"/tags",
  "google":"http://google.com"
};

Then you'd initiate the typeahead. The source and updater functions would be defined to handle 1) creating the typeahead data source array from the map object, and 2) navigate to the appropriate url when an item is selected..

$('.typeahead').typeahead({
  minLength:2,
  updater: function (item) {
        /* navigate to the selected item */
        window.location.href = data[item];
    },
  source: function (typeahead, query) {
    var links=[];
    for (var name in data){
        links.push(name); 
    }

    return links;
    }
});

Demo on Bootply

Upvotes: 5

Related Questions