I need help filtering a list of items based on user input. Currently, all the items are visible, but I want them to only show up when a user types a name.
I attempted changing the li style to block
, but it didn't work as expected.
li[i].style.display = "none";
I am a beginner in JS and currently taking some online courses.
function myFunction() {
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
* {
box-sizing: border-box;
}
#myInput {
background-image: url('/css/searchicon.png');
background-position: 10px 12px;
background-repeat: no-repeat;
width: 100%;
font-size: 16px;
padding: 12px 20px 12px 40px;
border: 1px solid #ddd;
margin-bottom: 12px;
}
#myUL {
list-style-type: none;
padding: 0;
margin: 0;
}
#myUL li a {
border: 1px solid #ddd;
margin-top: -1px; /* Prevent double borders */
background-color: #f6f6f6;
padding: 12px;
text-decoration: none;
font-size: 18px;
color: black;
display: block
}
#myUL li a:hover:not(.header) {
background-color: #eee;
}
<h2>Car Directory</h2>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for Cars" title="Type in a name">
<ul id="myUL">
<li><a href="#">Volvo</a></li>
<li><a href="#">BMW</a></li>
<li><a href="#">Mazda</a></li>
<li><a href="#">Toyota</a></li>
<li><a href="#">Yamaha</a></li>
<li><a href="#">Honda</a></li>
<li><a href="#">Dodge</a></li>
</ul>
If you can, please check out my pen here: https://codepen.io/emmabbb/pen/wvrpqbp