Reputation: 263
this is a simple program for searching an item from html list it works perfect but how can make it more advanced by adding few lines of codes to display a message like nothing was found or no result found if input didn't match an item from a list ?
function myFunction(){
let input = document.getElementById('myInput').value.trim();
let ul = document.getElementById("myUL");
let li = ul.getElementsByTagName("li");
let anch = document.getElementsByTagName('a');
let res = document.getElementById('result');
for(let i = 0 ; i < anch.length ; i++){
if(anch[i].innerText.toLowerCase().indexOf(input) > -1){
anch[i].style.display="";
anch[i].style.color="red";
}else{
anch[i].style.display="none";
}
}
}
<style>
#myInput {
background-image: url('/css/searchicon.png'); /* Add a search icon to input */
background-position: 10px 12px; /* Position the search icon */
background-repeat: no-repeat; /* Do not repeat the icon image */
width: 100%; /* Full-width */
font-size: 16px; /* Increase font-size */
padding: 12px 20px 12px 40px; /* Add some padding */
border: 1px solid #ddd; /* Add a grey border */
margin-bottom: 12px; /* Add some space below the input */
}
#myUL {
/* Remove default list styling */
list-style-type: none;
padding: 0;
margin: 0;
}
#myUL li a {
border: 1px solid #ddd; /* Add a border to all links */
margin-top: -1px; /* Prevent double borders */
background-color: #f6f6f6; /* Grey background color */
padding: 12px; /* Add some padding */
text-decoration: none; /* Remove default text underline */
font-size: 18px; /* Increase the font-size */
color: black; /* Add a black text color */
display: block; /* Make it into a block element to fill the whole list */
}
#myUL li a:hover:not(.header) {
background-color: #eee; /* Add a hover effect to all links, except for headers */
}
</style>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=0.1,shrink-to-fit=no">
<link type="text/css" href="/css" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Search</title>
</head>
<body>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
<ul id="myUL">
<li><a href="#">Adele</a></li>
<li><a href="#">Agnes</a></li>
</ul>
Upvotes: 4
Views: 1250
Reputation: 2190
Just use a variable to know if there were coincidences at the end of the loop.
var somethingFound=false;
...
for(let i = 0 ; i < anch.length ; i++){
if(anch[i].innerText.toLowerCase().indexOf(input) > -1){
...
somethingFound=true; //or somethingFound++ if you wan to keep a count
} else {
...
}
}
document.querySelector("#nothingFoundMessage").style.display=somethingFound?"block":"none"; //or something similar
Upvotes: 1