I'm currently trying to make a dynamic search bar with JavaScript which can search inside cards, the title and multiple keywords.
I currently have something but it doesn't seem to work properly. When I try searching for something even though the input value matches with the title or any of the keywords it still doesn't show it.
For example, if one card contains "docker" in the title and the other card contains "docx" in the title, and I'd type 'do'
it would show both but when I type 'doc', the docx card gets removed and it only shows the docker card.
Here I show only two cards, but in the project there are more of them:
function search_tool(el) {
const cards = document.querySelectorAll('.cards .card')
for (let card of cards) {
const texts_to_search_for = card.querySelectorAll('.card-title-left a, .card .keywords > span')
texts_to_search_for.forEach(txt => {
if (txt.innerText.toUpperCase().indexOf(el.value.toUpperCase()) > -1) {
card.style.display = ''
} else {
card.style.display = 'none'
}
})
}
}
<div class="cards">
<div class="card">
<div class="card-title">
<div class="card-title-left">
<a href="Card path">Card Title</a>
<i class="fa-solid fa-heart"></i>
</div>
</div>
<div class="keywords">
<span>keyword1</span>
<span>keyword2</span>
<span>keyword3</span>
<span>keyword4</span>
<span>keyword5</span>
</div>
</div>
<div class="card">
<div class="card-title">
<div class="card-title-left">
<a href="Card path">Card 2</a>
<i class="fa-solid fa-heart"></i>
</div>
</div>
<div class="keywords">
<span>keyword1</span>
<span>keyword2</span>
<span>keyword3</span>
<span>keyword4</span>
<span>keyword5</span>
</div>
</div>
</div>
It runs every time we type something in the input. el parameter is the input element.
I wanted to know if there's something I could do to make it work while having this code or do I need to remove the code completely.
Thank you in advance.
The problem seems to be:
I'd suggest rewriting to use Array methods, as follows – with explanatory comments in the code – specifically using
Array.prototype.some()
:JS Fiddle demo.
However, I would personally rewrite the above to the following, with explanatory comments in the code:
JS Fiddle demo.
References:
Array.prototype.forEach()
.Array.prototype.map()
.Array.prototype.some()
.document.querySelector()
.document.querySelectorAll()
.Element.querySelector()
.Element.querySelectorAll()
.String.prototype.includes()
.String.prototype.toUpperCase()
.String.prototype.trim()
.