Reputation: 147
<!-- display only the sentences in a list whose starting letter matches the letter selected from the drop down list -->
$("document").ready(function() {
$("#alphalist").change(function(){
$(".lists").hide();
$("#" + $(this).val()).show();
});
});
<!-- code to search from currently displayed list -->
function myFunction() {
var input, filter, ul, li, a, i, txtValue;
input = $("#searchbox");
filter = input.value.toUpperCase();
ul = $("ul");
li = ul.$("li");
for (i = 0; i < li.length; i++) {
a = li[i].$("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
}
else {
li[i].style.display = "none";
}
}
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<select class="dropdown" id="alphalist">
<option value="a" selected>A</option>
<option value="b">B</option>
</select>
<input class="input" type="text" id="searchbox" placeholder="Search...." onkeyup="myFunction()"/>
<div class="lists" id="a">
<ul id="alist">
<li><a href="#">All is well</a></li>
<li><a href="#">Any body can dance</a></li>
<li><a href="#">As you like it</a></li>
</ul>
</div>
<div class="lists" id="b" style="display:none">
<ul id="blist">
<li><a href="#">Before the sunset</a></li>
<li><a href="#">Blink your eyes</a></li>
<li><a href="#">Bukkle up</a></li>
</ul>
</div>
</body>
</html>
This is just a small example. Here I created two options(A & B) using select tag and two ul lists. First list contains sentences starting with letter 'a' and second list contains sentences starting with letter 'b'. The first jquery code displays list with sentences whose starting letter matches the letter selected from dropdown options.
But the problem is with searching. Consider selecting option B and it'll lists senetences starting with B. After that, if I write something in search bar, I want to display the matching senetences from currently displayed list(senetences starting with b). I tried, but not getting the result I wanted. Please help me.
Upvotes: 0
Views: 221
Reputation: 36
I've updated your code for searching.
$("#searchbox").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("div.lists li").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
Upvotes: 1