HTML in Bootstrap-3-Typeahead
add html elements in typeahead
by Nofiden Noble
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.0/bootstrap3-typeahead.js"></script>
<div class="dropdown">
<input class="form-control" id="typeahead" type="text" data-provide="typeahead">
</div>
SCSS
.dropdown {
margin: 50px auto;
max-width: 300px;
}
.dropdown-menu {
li {
&+ li {
margin-top: 10px;
}
a {
padding: 5px 0 5px 55px;
min-height: 50px;
position: relative;
white-space: normal;
}
}
.typeahead-inner {
.item-img {
width: 40px;
height: 40px;
position: absolute;
left: 5px;
top: 5px;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
border-radius: 5px;
}
.item-heading {
display: inline-block;
vertical-align: middle;
line-height: 18px;
}
}
}
JavaScript
var typeahead = {
typeaheadInit: function() {
var jsonData = [{
'id': 1,
'name': 'Parajanov Museum',
'image': 'http://tinyurl.com/zrey5yj'
}, {
'id': 2,
'name': 'Parajanov’s Movie',
'image': 'http://tinyurl.com/zrey5yj'
}, {
'id': 3,
'name': 'S Parajanov’s about his series of Giocondas',
'image': 'http://tinyurl.com/zrey5yj'
}, {
'id': 4,
'name': 'S Parajanov’s about the colore of pomegranate',
'image': 'http://tinyurl.com/zrey5yj'
}, {
'id': 5,
'name': 'George Michael',
'image': 'http://tinyurl.com/zrey5yj'
}];
var productNames = [];
$.each(jsonData, function(index, product) {
productNames.push(product.name + "#" + product.image + "#" + product.id);
});
$('#typeahead').typeahead({
source: productNames,
highlighter: function(item) {
var parts = item.split('#'),
html = '<div><div class="typeahead-inner" id="' + parts[2] + '">';
html += '<div class="item-img" style="background-image: url(' + parts[1] + ')"></div>';
html += '<div class="item-body">';
html += '<p class="item-heading">' + parts[0] + '</p>';
html += '</div>';
html += '</div></div>';
var query = this.query;
var reEscQuery = query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var reQuery = new RegExp('(' + reEscQuery + ')', "gi");
var jElem = $(html);
var textNodes = $(jElem.find('*')).add(jElem).contents().filter(function() {
return this.nodeType === 3;
});
textNodes.replaceWith(function() {
return $(this).text().replace(reQuery, '<strong>$1</strong>');
});
return jElem.html();
},
updater: function(selectedName) {
var name = selectedName.split('#')[0];
return name;
}
});
},
initialize: function() {
var _this = this;
_this.typeaheadInit();
...