I would like to compare a input against li elements but for some reason it's only checking the last li element. You can see this when running the script below everything with "test" works fine but not for "example" or "example 2"
$(document).ready(function() {
var $input = $('#autocomplete');
$(document).on('keyup', $input, function() {
var $val = $input.val().trim(),
$select = $('.autocomplete-content');
// Check if the input isn't empty
if ($val != '') {
$select.children('li').each(function() {
var $li = $(this),
$html = $li.html(),
$text = $li.text().trim();
// Set input value
$li.click(function() {
$input.val($text);
});
// Check if the value has at least 1 match else hide
if ($text.indexOf($val) !== -1) {
// Remove class hide when input changes and finds a match
if ($li.hasClass('hide')) {
$li.removeClass('hide');
}
// Unhide "ul.autocomplete-content"
if ($select.hasClass('hide')) {
$select.removeClass('hide'); // Show options
}
} else {
$li.addClass('hide');
$select.addClass('hide'); // Hide options
}
});
} else {
$select.addClass('hide');
}
});
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="autocomplete" class="autocomplete">
<ul class="autocomplete-content hide">
<li><img src="test.jpg"> example</li>
<li><img src="test.jpg"> example 2</li>
<li><img src="test.jpg"> test</li>
</ul>
So my question is how can I compare the input against each li element. Thanks in advance.
Update
Something I forgot to mention was that in the li
element could be an img
thats the reason why I used $li.text()