I made a searchbar filter and a filter with input buttons. The searchbar filter works but the input filter doesn't. How is that possible? Here you see the searchbar
code and underneath there is the input button filter. First I made that filter with buttons
who filter on the classnames but there are too many possibilities so with filtering on textContent
it's the easiest I thought.
JavaScript
//searchbar
function liveSearch() {
let search_query = document.getElementById('myInput').value;
//Use innerText if all contents are visible
//Use textContent for including hidden elements
for (var i = 0; i < sheets.length; i ) {
if (
sheets[i].textContent.toLowerCase().includes(search_query.toLowerCase())
) {
sheets[i].classList.remove('is-hidden');
} else {
sheets[i].classList.add('is-hidden');
}
}
}
document.getElementById('myInput').oninput = liveSearch;
//buttons filter
let knop = document.querySelectorAll('#btn');
knop.forEach((btn) =>
btn.addEventListener('click', (e) => {
e.target.classList.toggle('active');
liveSearch2();
}),
);
function liveSearch2() {
let button = document.getElementById('btn').value;
for (var i = 0; i < sheets.length; i ) {
if (sheets[i].textContent.toLowerCase().includes(button.toLowerCase())) {
sheets[i].classList.remove('is-hidden');
} else {
sheets[i].classList.add('is-hidden');
}
}
}
document.getElementById('btn').oninput = liveSearch2;
<input type="text" id="myInput" placeholder="Search for music..." title="Type in a name" />
<div id="myBtnContainer">
<p >Genre</p>
<input value="Barok" type="button" id="btn"></input>
<input value="Classic" type="button" id="btn"></input>
<input value="Rennaisance" type="button" id="btn"></input>
<input value="Romantic" type="button" id="btn"></input>
<input value="Movies" type="button" id="btn"></input>
</div>`
CodePudding user response:
You're always getting the value of the first button when you do
let button = document.getElementById('btn').value;
This doesn't get the button that the user clicked on.
Use e.target
to get the button that the user clicked on, and get its value.
knop.forEach((btn) =>
btn.addEventListener('click', (e) => {
e.target.classList.toggle('active');
liveSearch2(e.target.value);
}),
);
function liveSearch2(button) {
for (var i = 0; i < sheets.length; i ) {
if (sheets[i].textContent.toLowerCase().includes(button.toLowerCase())) {
sheets[i].classList.remove('is-hidden');
} else {
sheets[i].classList.add('is-hidden');
}
}
}