I am looking to add a search functionality to filter through a list of accordions and their contents on my HTML page. I want the search box to be able to search both the accordion titles and the content within each accordion. This is my first time posting a question on Stackoverflow, so I apologize if it's not clear.
Below is the code showing how I create and display the accordions when a user clicks on a title. (I have a single accordion in the HTML that I clone using a JavaScript file.)
// HTML code:
<input type="search" id="accordion_search_bar" placeholder="Search"/>
<div id="accordions">
<div id="accID1" class="AccordionContainer">
<button id="accID" class="accordion"></button>
<div class="panel" id="panel1">
</div>
// JavaScript code:
for (a = 0; a < acc.length; a++) {
acc[a].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight){
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
// Additional JavaScript for the search feature:
$(function() {
var searchTerm, panelContainerId;
// Create a new case-insensitive 'contains' selector
$.expr[":"].containsCaseInsensitive = function(n, i, m) {
return (
jQuery(n)
.text()
.toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0
);
};
$("#accordion_search_bar").on("change keyup paste click", function() {
searchTerm = $(this).val();
$("#accordions > .AccordionContainer").each(function() {
panelContainerId = "#" + $(this).attr("id");
$(
panelContainerId + ":not(:containsCaseInsensitive(" + searchTerm + "))"
).hide();
$(
panelContainerId + ":containsCaseInsensitive(" + searchTerm + ")"
).show();
});
});
});
In essence, I am trying to implement a search bar that can search through the buttons of all accordions and also look within every panel created for each accordion.