FAQ_JavaScript
document.addEventListener('DOMContentLoaded', function() {
const searchInput = document.getElementById('searchInput');
const results = document.getElementById('results');
searchInput.addEventListener('input', function() {
const searchText = searchInput.value.toLowerCase();
const faqSections = document.querySelectorAll('.accordion');
let hasResults = false; // 検索結果があるかどうかを追跡するフラグ
// 検索結果をクリア
results.innerHTML = '';
// 検索テキストが空の場合は処理を終了
if (!searchText) {
return;
}
// 各FAQセクションを検索
faqSections.forEach((section, sectionIndex) => {
const questions = section.querySelectorAll('.accordion-open'); /*質問から検索結果を出力(回答は検索範囲に含めない)*/
questions.forEach((question, questionIndex) => {
if (question.textContent.toLowerCase().includes(searchText)) {
hasResults = true; // 検索結果が見つかった
const resultItem = document.createElement('li');
const link = document.createElement('a');
const checkboxId = `check${sectionIndex * 4 + questionIndex + 1}`;
link.href = `#${checkboxId}`;
link.textContent = question.textContent;
resultItem.appendChild(link);
results.appendChild(resultItem);
// リンクをクリックしたときの処理
link.addEventListener('click', function(e) {
e.preventDefault();
const targetCheckbox = document.getElementById(checkboxId);
if (targetCheckbox) {
// チェックボックスをチェックしてからスクロール
targetCheckbox.checked = true;
const targetPanel = targetCheckbox.nextElementSibling;
if (targetPanel) {
targetPanel.scrollIntoView({ behavior: 'smooth' });
}
}
});
}
});
});
// 検索結果がない場合はNo dateを表示
if (!hasResults) {
results.textContent = 'No date';
}
});
});
この記事が気に入ったらサポートをしてみませんか?