I want to ensure that if the input field is empty, no results are displayed. Currently, when you enter a name and then delete it, all the results in the array are shown.
const characters = [{
first_name: "Abraham",
last_name: "Lincoln",
img: "https://upload.wikimedia.org/wikipedia/commons/a/ab/Abraham_Lincoln_O-77_matte_collodion_print.jpg"
},
{
first_name: "Johnny",
last_name: "Bravo",
img: "https://ia.media-imdb.com/images/M/MV5BYTg4MDkwODgtYTBlNy00Yjc2LTg4NTYtZGE5YmFhYjY5NzU2XkEyXkFqcGdeQXVyNTM3MDMyMDQ@._V1_.jpg"
},
{
first_name: "Barney",
last_name: "Rubble",
img: "https://upload.wikimedia.org/wikipedia/en/e/e2/Barney_Rubble.png"
}
];
let searchInput = document.getElementById('searchInput');
searchInput.addEventListener('keyup', filterNames);
function filterNames() {
let filterValue = document.getElementById('searchInput').value.toUpperCase();
let output = '';
for (let i = 0; i < characters.length; i++) {
let firstName = characters[i].first_name.toUpperCase();
if (firstName.indexOf(filterValue) > -1) {
output +=
'<div class="card">' +
'<div class="img-container text-center">' +
'<img src="' + characters[i].img + '" width=180 height=180 />' +
'</div>' +
'<div class="text-center">' +
'<h5>' + characters[i].first_name + ' ' + characters[i].last_name + '</h5>' +
'</div>' +
'</div>';
}
}
document.getElementById('characters').innerHTML = output
};
.card {
display: inline-block;
margin-right: 12px;
float: left;
}
<div>
<input type="text" id="searchInput" placeholder="Who do you seek?" />
</div>
<div id="characters"></div>
Check out the demo on jsfiddle
Your assistance is greatly appreciated.