Display List Item by name with a Search List

Viewed 30

I am working on a Search List to display Continents and their population when the name of a continent is typed on the search bar. This is what I want to happen;

  1. If "a" is typed on the search bar, it should display only the continents starting starting with letter "a" (e.g. Africa, Antarctica, Asia).

  2. And if "an" is typed on the search bar, Antarctica will be displayed.

  3. If "sou" is typed on the search bar, South America should be displayed.

See my code below, it is not giving me what I expect above. Please someone should help me with a better JavaScript code. Thank you

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
  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;
  display: none;
}

#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;
}
</style>
</head>
<body>

<h2>World Population by Continent</h2>

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for Continent.." title="Type in a name">

<ul id="myUL">
  <li><a href="#">Asia - 4,641,054,775</a></li>
  <li><a href="#">Africa - 1,340,598,147</a></li>
  <li><a href="#">Europe - 747,636,026</a></li>
  <li><a href="#">North America - 592,072,212</a></li>
  <li><a href="#">South America - 430,759,766</a></li>
  <li><a href="#">Oceania - 43,111,704</a></li>
  <li><a href="#">Antarctica - 0</a></li>
</ul>

<script>
function myFunction() {
    var x, input, filter, ul, li, a, i, txtValue;
    x = document.getElementById("myUL");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
    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";
        }
    }
}
</script>

</body>
</html>

0 Answers
Related