+ 1
JavaScript Specific Search Bar - SOLVED
So I'm trying to code a search bar for a glossary I'm making. It's got terms and their definitions. I want the search bar to search only the terms and then display relevant terms and definitions. I don't want it to search the definitions for the words. Anyone wanna help me with the js part? I have very little js knowledge. I'm using the dl element for my glossary with the dt and dd combined under a div if that helps at all.
2 odpowiedzi
+ 4
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Glossary Search</title>
</head>
<body>
<h2>Glossary</h2>
<input type="text" id="searchInput" placeholder="Search terms">
<div id="glossary">
<dl>
<div>
<dt>Term 1</dt>
<dd>Definition 1</dd>
</div>
<div>
<dt>Term 2</dt>
<dd>Definition 2</dd>
</div>
<!-- Add more terms and definitions here -->
</dl>
</div>
<script>
document.getElementById('searchInput').addEventListener('input', function() {
var searchTerm = this.value.toLowerCase();
var glossaryItems = document.querySelectorAll('#glossary dt');
glossaryItems.forEach(function(item) {
var term = item.textContent.toLowerCase();
var parentDiv = item.parentElement;
if (term.includes(searchTerm)) {
parentDiv.style.display = 'block';
} else {
parentDiv.style.display = 'none';
}
});
});
</script>
</body>
</html>
+ 1
You're amazing! Thank you so much! Mind if I copy-paste you're code? I won't use it for anything monetized or anything like that