I have implemented a search functionality and it’s working if we search the keyword by typing.
<input type="text" class="txtInput" id="searchTheKey" placeholder="Enter the keywords to search.....">
</label>
<ul id="matchKey">
<li id="subjectName">JavaScript</li>
<li id="teacherName"><a href="#">John Smith</a></li>
<li id="subjectName">Java</li>
<li id="teacherName"><a href="#">David Miller</a</li>
<li id="subjectName">MongoDB</li>
<li id="teacherName"><a href="#">Carol Taylor</a></li>
</ul>
<script>
$("#searchTheKey").on('keyup', function(){
var value = $(this).val().toLowerCase();
$("#matchKey li").each(function () {
if ($(this).text().toLowerCase().search(value) > -1) {
$(this).show();
$(this).prev('.subjectName').last().show();
} else {
$(this).hide();
}
});
})
</script>
But in the case of assigning value in the input box directly, the search functionality is not working.
example : $(".txtInput").val("MongoDB");
is there any way to solve this issue, that this should work in both case.
>Solution :
You can add .trigger("keyup") to your $(".txtInput").val("MongoDB")
Demo
$("#searchTheKey").on('keyup', function() {
var value = $(this).val().toLowerCase();
$("#matchKey li").each(function() {
if ($(this).text().toLowerCase().search(value) > -1) {
$(this).show();
$(this).prev('.subjectName').last().show();
} else {
$(this).hide();
}
});
})
$(".mongo").click(function() {
$(".txtInput").val("MongoDB").trigger("keyup")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="txtInput" id="searchTheKey" placeholder="Enter the keywords to search.....">
<ul id="matchKey">
<li id="subjectName">JavaScript</li>
<li id="teacherName"><a href="#">John Smith</a></li>
<li id="subjectName">Java</li>
<li id="teacherName"><a href="#">David Miller</a></li>
<li id="subjectName">MongoDB</li>
<li id="teacherName"><a href="#">Carol Taylor</a></li>
</ul>
<button class="mongo">search for mongo</button>