-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
56 lines (49 loc) · 2.32 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
document.addEventListener("DOMContentLoaded", function() {
const searchInput = document.getElementById("search");
const resultsContainer = document.getElementById("results");
const errorContainer = document.getElementById("error");
// Fetch the JSON data
fetch('answers.json')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => {
// Store data in a variable
const questionsAndAnswers = data;
// Function to display results
function displayResults(results) {
resultsContainer.innerHTML = '';
results.forEach(result => {
const resultDiv = document.createElement('div');
resultDiv.classList.add('result');
const questionDiv = document.createElement('div');
questionDiv.classList.add('question');
questionDiv.textContent = result.Question;
const answerDiv = document.createElement('div');
answerDiv.classList.add('answer');
answerDiv.textContent = result.Answer;
resultDiv.appendChild(questionDiv);
resultDiv.appendChild(answerDiv);
resultsContainer.appendChild(resultDiv);
});
}
// Event listener for search input
searchInput.addEventListener('input', function() {
const query = searchInput.value.toLowerCase();
const filteredResults = questionsAndAnswers.filter(qa =>
qa.Question.toLowerCase().includes(query) ||
qa.Answer.toLowerCase().includes(query)
);
displayResults(filteredResults);
});
// Display all results initially
displayResults(questionsAndAnswers);
})
.catch(error => {
errorContainer.innerText = 'Failed to fetch data: ' + error.message;
console.error('Error fetching the JSON data:', error);
});
});