JB Bands + Algolia
by Todd Levy
HTML
<script src="https://2ab9pu2w8o9xpg6w26xnz04d-wpengine.netdna-ssl.com/wp-content/plugins/jb-algolia-frontend/lib/algoliasearch/3.30.0/algoliasearch.min.js"></script>
<script src="https://2ab9pu2w8o9xpg6w26xnz04d-wpengine.netdna-ssl.com/wp-content/plugins/jb-algolia-frontend/lib/autocomplete.js-master/dist/autocomplete.jquery.min.js"></script>
<table>
<tr>
<td>
<input type="text" id="band-name" autcomplete="password" placeholder="Type band name…"></td>
<td>
<input type="text" id="band-id" value="" placeholder="BAND ID" disabled="disabled">
</td>
</tr>
</table>
CSS
input {
padding: 5px;
}
.ap-dropdown-menu {
padding: 0 5px;
background-color: #e6e6e6;
}
.ap-header,
.ap-suggestion a {
display: block;
padding: 10px 0;
}
.ap-suggestion a {
color: #0000ff;
border-top: 1px solid rgba(0, 0, 0, .2);
}
.ap-suggestion a:hover {
cursor: pointer;
}
JavaScript
// set up the algolia client
var jb_algolia_client = algoliasearch('W5G06A3QFA', '233d539a40f129adcd4e74bb036af762');
// set up the bands index
var bands_index = jb_algolia_client.initIndex('bands_production');
// handler for the typeahead
var handle_band_typeahead = {
source: $.fn.autocomplete.sources.hits(bands_index, {
hitsPerPage: 10
}),
displayKey: 'post_title',
name: 'bands',
templates: {
header: '<div class="ap-header"><span style="text-transform:none;">Click the band name to select it.</span></div>',
suggestion: function(suggestion) {
return '<a class="select-band" data-bandid="' + suggestion.ID + '">' + suggestion._highlightResult.post_title.value + '</a>';
},
empty: function() {
return '<div class="ap-empty">No bands match that name.</div>';
},
footer: function() {
// if you need stuff in footer, return it here.
}
}
};
// document ready
$(function() {
// cache the band name search field
var $band_name_field = $('#band-name');
$(document).on('click', '.select-band', function(e) {
// get the band id from the clicked autocomplete result
var band_id = $(this).attr('data-bandid');
// reset the band name autocomplete
$band_name_field.autocomplete('close').autocomplete('val', '').blur();
// populate the band id field
$('#band-id').attr('value', band_id);
});
$band_name_field.autocomplete({
debug: true,
hint: false,
cssClasses: {
prefix: 'ap'
}
}, [handle_band_typeahead]);
}); // end document ready