This is my first question here, so I apologize if anything is not as it should be, but I am coding a tool that takes a rather large unordered list and displays them as a series of checkboxes. I have a function that allows a user to search through the list by hiding all li elements and then making visible only the matching elements (this is accomplished with the jquery function show() and hide()). It works great, but I have noticed that when the elements hide, the list does not resize, creating a situation where if the searched element was at the bottom of the list, one would have to scroll down to find the result.
For example
- 1
- 2
- 3
- 1
[complete search button]
After search for "1" becomes
- 1
- (blank space)
- (blank space)
- 1
I would like it to reformat the list to simply
- 1
- 1 [complete search button]
but without the blank spaces. I am fairly new to javascript and jquery so any advice on how to approach this will be really appreciated!
CodePudding user response:
It's not clear what is not working. Here is an example that might fit your use case.
$(function() {
$("button").click(function() {
$(".items li").show();
if ($(".search").val() != "") {
$(".items li").not(":contains('" $(".search").val() "')").hide();
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Search</label> <input type="text" /> <button>Go</button>
<ul >
<li>1</li>
<li>2</li>
<li>3</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
Please provide a Minimal, Reproducible Example: https://stackoverflow.com/help/minimal-reproducible-example