Enhance the interactivity of Javascript results by making them clickable

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.

Answer №1

you have the option to utilize

document.addEventListener('click', (e) => {
  if(e.target....){}
)

for implementing an event for a dynamic element, and it is advisable to utilize setTimeout in the input event so that if a user types 10 characters within xx millisecond, the request will only be sent to the server once.

// Obtain Elements
const search = document.querySelector('#search');
const matchList = document.querySelector('#match-list');

// Search JSON Airport file
const searchFlights = async searchText => {
    //const response = await fetch('airports.json');
    //const data = await response.json();
    const data = [{"iata":"UTK","lon":"169.86667","iso":"MH","status":1,"name":"Utirik Airport","continent":"OC","type":"airport","lat":"11.233333","size":"small"},{"iata":"FIV","iso":"US","status":1,"name":"Five Finger CG Heliport","continent":"NA","type":"heliport","size":null},{"iata":"FAK","iso":"US","status":1,"name":"False Island Seaplane Base","continent":"NA","type":"seaplanes","size":null},{"iata":"BWS","iso":"US","status":0,"name":"Blaine Municipal Airport","continent":"NA","type":"closed","size":null},{"iata":"WKK","lon":"-158.61111","iso":"US","status":1,"name":"Aleknagik \/ New Airport","continent":"NA","type":"airport","lat":"59.27778","size":"medium"},{"iata":"TSS","iso":"US","status":1,"name":"East 34th Street Heliport","continent":"NA","type":"heliport","size":null},{"iata":"FOB","lon":"-123.79444","iso":"US","status":1,"name":"Fort Bragg Airport","continent":"NA","type":"airport","lat":"39.474445","size":"small"},{"iata":"ABP","lon":"141.1","iso":"PG","status":1,"name":"Atkamba...
    
    // 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">
                <h6 class="data-input">${match.iata} | ${match.name}</h6>
            </div>`).join('');

        matchList.innerHTML = html;
    }
};

// Event listener on any event, can also be key up, down or whatever
let timer;
search.addEventListener('input', () => {
  if(timer) clearTimeout(timer);
  timer = setTimeout(searchFlights, 300, search.value);
});

document.addEventListener('click', (e) => {
  if(e.target.classList.contains('data-input')){
    search.value = e.target.textContent;
    document.querySelector('#match-list').innerHTML = "";
  }
});
.data-input {cursor: pointer;color: blue;}
.data-input:hover {text-decoration: underline;}
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" />

<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve the nearest or preceding object regardless of the document's layout using jQuery?

Here are some examples to illustrate the concept: <ul> <li id="o1" class="elem">apple</li> <li id="o2" class="elem">banana</li> <li id="o3" class="elem">orange</li> </ul> **$('#o2').exact ...

Ways to retrieve information from a URL using the .get() method in a secure HTTPS connection

As I work on handling user input from a form using node.js, express, and bodyParser, I encounter an issue. Even after using console.log(req.body), the output is {}. This is puzzling as there is data in the URL when the form is submitted successfully at htt ...

The React forwardRef Higher Order Component is failing to provide a reference to the container element

I'm currently working on creating a higher order component (HOC) for closing an element when clicked outside of its space, known as a generic close on outside solution. In my understanding, this can be achieved using forwardRef and HOC implementation ...

I find myself struggling to manage my javascript dependencies

Currently, I am utilizing NPM along with various angular packages. As per the tutorial on Basic Grid Part 1 at this link, I am encountering challenges. This is my file directory structure: D:/nodeStuff/uiGrid includes: node_modules uigrid.css uigrid.h ...

The memory usage steadily increases when you refresh data using the anychart gantt chart

I have a basic anychart code to update a gantt chart every second: function initializeSchedule(){ anychart.onDocumentReady(function () { anychart.data.loadJsonFile("../scheduler?type=getschedule", function (data) { documen ...

Tips for retrieving selected items in an array object

Within my UI, I have a select field that, on change, populates corresponding data in a div with nested ul and li elements. What I am attempting to achieve is to convert the selected items within the list (which include checkboxes) into an object of arrays ...

Instructions for adding the more-vert icon from material-ui into a react project

I've been searching tirelessly, but I can't seem to locate it. Where exactly is the location of this in material-ui? I've seen others using it. Any assistance would be greatly appreciated. My initial thought was: import MoreVertIcon from & ...

gulp-watch does not monitor files that are newly created or deleted

Currently working on a task: gulp.task('assetsInject', function () { gulp.src(paths.index) .pipe(plugins.inject( gulp.src(paths.scripts, {read: false}), { addRootSlash: false } ...

Issues with Kendo Grid showing incomplete data and columns

Having trouble populating a kendo grid with column titles, as some columns appear empty despite having data when checked in the console log. $(function () { $("#uploadBtn").click(function () { var url = window.rootUrl + 'Upload/UploadM ...

Using Jquery to manipulate arrays based on options selected from a dropdown menu

I am currently working on a feature that suggests tags based on the selected category. This involves using a select box to choose a category and then displaying sub-categories in a list. Here is the current setup: <select id="categorySelect"> < ...

Guide to updating text color in marquee tag with each reload

Seeking assistance in addressing the following issues... On each refresh, I want to change the text color within a marquee tag by utilizing a JavaScript function. I have obtained a color code like #18EEC5... however, when attempting to call the script fun ...

How to iteratively process JSON array using JavaScript?

I am currently attempting to iterate through the JSON array provided below: { "id": "1", "msg": "hi", "tid": "2013-05-05 23:35", "fromWho": "<a href="/cdn-cgi/l/email-pro ...

What is the best approach to resolving the MongoServerError: E11000 duplicate key error?

Index.Js File: const cookieSession = require("cookie-session"); const express = require("express"); const app = express(); const helmet = require("helmet"); const morgan = require("morgan"); const dotenv = require(&q ...

Axios fails to capture and transmit data to the client's end

I created a backend using Express to retrieve Instagram feed images and then send their URLs to my front end, which is built with ReactJs. When I fetch the image URLs with instagram-node and send them to the front end, everything functions as expected. How ...

Ways to handle the res.locals object in a request manipulation

I am currently utilizing node-restful in my project and I am looking to replace my date properties with the help of moment. However, when I attempt the following approach; var QuestionResource = app.user = restful.model('Question', questionSche ...

Is there a way to conceal the parameters in the PHP GET method?

How to convert PHP GET method URL to a cleaner format? example.com/example.php?name=45 to example.com/example.php/45 Is it possible to achieve this using the .htaccess file? ...

Is it possible to automatically set focus on the input box in an html tag multiple times instead of just once with autofocus?

Currently, I am developing an online editor that allows users to quickly edit individual words. My approach involves replacing specific words with input boxes containing the word for direct editing by users. In order to streamline the process and ensure e ...

The jQuery slider's next button is not functioning as intended

jQuery('#slider-container').bjqs({ 'animation' : 'slide', 'width' : 1060, 'height' : 500, 'showControls' : false, 'centerMarkers' : false, animationDuration: 500, rotationS ...

Encountering the error message "Unable to instantiate User: constructor not found" while testing API functionality for

Currently, I am in the process of integrating my backend with MongoDB ATLAS. In order to achieve this, I am utilizing express, mongoose, and node.js for testing purposes. Specifically, I am focusing on testing my API routes, such as adding a user. Below i ...

Perform a series of database queries one after the other, ensuring they are completed before

Although the database queries themselves are working fine, I am facing an issue with executing them sequentially in Node. Here is an example of the queries I need to execute in order: DELETE FROM myTable; INSERT INTO myTable(c1, c2, c3) VALUES (x, y, z); ...