I have a live search feature with jQuery on my website. The search works fine and displays results, but when I click on a result, I want the value to be shown in my input field. Additionally, once I click outside of the input field, the result should hide (like an autocomplete feature), but I've been struggling to implement this functionality.
I cannot use an autocomplete plugin because I need to display images in my search results.
$(document).ready(function() {
$("#srehberText").keyup(function() {
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(),
count = 0;
if (!filter) {
$(".commentlist li").fadeOut();
return;
}
var regex = new RegExp(filter, "i");
// Loop through the comment list
$(".commentlist li").each(function() {
// If the list item does not contain the text phrase, fade it out
if ($(this).text().search(regex) < 0) {
$(this).hide();
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).fadeIn();
count++;
}
});
});
});
ol {
list-style-type: none;
padding: 0;
width: 600px;
}
input {
width: 600px;
padding: 12px;
border: 1px solid #ccc;
color: #999;
}
li {
display: none;
}
li img {
margin-right: 5px;
}
li a {
display: block;
text-decoration: none;
color: #666;
font: 16px tahoma;
padding: 4px;
}
li a:hover {
background: #fffff0;
color: #333;
}
<input type="text" class="text-input" id="srehberText" placeholder="Start typing the region" />
<ol class="commentlist">
<li>
<a href="#"><img src="region-image-url-here">Germany</a>
</li>
<li>
<a href="#"><img src="region-image-url-here">Russia</a>
</li>
<li>
<a href="#"><img src="region-image-url-here">Turkey</a>
</li>
<li>
<a href="#"><img src="region-image-url-here">England</a>
</li>
<li>
<a href="#"><img src="region-image-url-here">Netherlands</a>
</li>
<li>
<a href="#"><img src="region-image-url-here">USA</a>
</li>
<li>
<a href="#"><img src="region-image-url-here">Korea</a>
</li>
</ol>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>