I'm new to JavaScript and facing a challenge. I have a JSON file that I'm using to retrieve data. I now want to make the search results clickable so they can be directly inserted into an input field. Eventually, I plan on incorporating them into a card where all inputs can be saved.
Here is the HTML structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<title>Test Async</title>
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-md-6 m-auto">
<h3 class="text-center mb-3">Flights</h3>
<div class="form-group">
<input id="search" type="text" class="form-control form-control-lg" placeholder="Enter IATA Code, or Airport">
</div>
<div id="match-list"></div>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
And here's the accompanying JavaScript code:
// Get Elements
const search = document.querySelector('#search');
const matchList = document.querySelector('#match-list');
// Search JSON Airport file asynchronously
const searchFlights = async searchText => {
const response = await fetch('airports.json');
const data = await response.json();
// Filter Data with regex
let results = data.filter(result => {
const regexIata = new RegExp(`^${searchText}`, 'gi');
const regexName = new RegExp(`${searchText}`, 'gi');
if (result.name != null) {
return result.iata.match(regexIata) || result.name.match(regexName);
}
});
if (searchText.length === 0) {
matches = []; // Empty array if no result
matchList.innerHTML = ''; // Shows nothing when serachbar is empty
}
else {
outputHtml(results);
}
};
const outputHtml = results => {
if(results.length > 0) {
const html = results.map(match =>
`<div class="card card-body mb-1">
<a href="#" class="data-input"><h6>${match.iata} | ${match.name}</h6></a>
</div>`).join('');
matchList.innerHTML = html;
}
};
// Event listener for any input event
search.addEventListener('input', () => searchFlights(search.value));
A snippet from the JSON file is provided above.