When I start typing the name of a golf course in a search box using Typeahead.js and Bloodhound, the dropdown correctly shows just the name of the golf course.
Problem
- When I click on
.tt-suggestion
, which contains the course's name, the text that populates the search box is the golf course object instead of obj.name, which is stored invar courses = []
scripts.js
<script type="text/javascript">
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
var courses = [
{% for content in COPY.courses%}
{
"name": "{{content.name}}",
"url": "/courses/{{content.slug}}",
},
{% endfor %}
];
var source = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: courses
});
source.initialize();
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'courses',
source: source.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">We could not find any golf courses with that name</div>'
],
suggestion: function(data) {
return '<div><a href="' + course.url + '">' + course.name + '</a></div>';
}
}
});
</script>
index.html
<div class="search search--home">
<label class="search__label">Search all courses</label>
<i class="fa fa-search" aria-hidden="true"></i>
<input class="typeahead" type="search" name="" placeholder="Search all golf courses">
</div>