The reason for the lack of auto complete functionality in this specific Bootstrap example remains unclear

I've been attempting to implement an auto-complete dropdown feature with dynamic data, but I'm facing an issue where no suggestions are displayed in the dropdown. I found this example on Datalists: https://getbootstrap.com/docs/5.1/forms/form-control/ which works perfectly fine with predefined option tags.

<label for="exampleDataList" class="form-label">Datalist example</label>
   <input class="form-control" list="datalistOptions" id="exampleDataList" placeholder="Type to search...">
   <datalist id="datalistOptions">
       ... dynamic data here
   </datalist>

I am able to receive data from the PHP script and access it correctly, but I suspect that the issue may be related to a delay in fetching the data. The HTML might expect the data to already be present when loaded, which could explain why it works with existing data.

Below is the JavaScript code within the fetch function responsible for dynamically creating the option tags:

 var select = document.getElementById("datalistOptions");
 select.innerHTML = "";

 for (var key in data['result']) {
    var val = data['result'][key];
    if (data['result'].hasOwnProperty(key) && key != "error") {
       var val = data['result'][key];
      
       if (val != "") {
          var option = document.createElement("option");              
          option.value = val.id;
          select.appendChild(option);
       }
    }
 }

Update: I made some modifications to the JavaScript code. Now it utilizes appendChild instead of the add function. The previous version was not adding any options to the datalist. Although appendChild does add options to the list, it doesn't display them.

Answer №1

This presents a simplified version of what you are attempting to accomplish. Take this structure, integrate your conditions, and format the data accordingly.

     var cities = ["Haifa", "Tel Aviv", "Jerusalem"];
        var select = document.getElementById("datalistOptions");
        select.innerHTML = "";
        for (var index in cities) {
                var option = document.createElement("option");
                option.label = cities[index];
                option.value = cities[index];
                select.appendChild(option);
          }

Be sure to include an onclick event that calls your script, as it may be the missing piece causing issues - Consider something along these lines:

<input onclick="createDatalist()" class="form-control" list="datalistOptions" id="exampleDataList" placeholder="Type to search...">

The function name 'createDatalist()' is defined within the script.

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

Encountered an issue while building npm: "Error: Unable to locate module @restart/context

Lately, I've encountered an issue with npm build after upgrading to the latest version of react-bootstrap (1.0.0-beta.6). While creating an optimized production build... Failed to compile. Module not found: '@restart/context/forwardRef'. P ...

Material Grid adamantly refused to follow the typical horizontal layout, defying its default behavior

I recently discovered Material-UI and have been trying to get two components to display side by side. However, no matter what I try, it always ends up looking like this: https://i.stack.imgur.com/w1Wyh.png Even though it is the default behavior, the Mate ...

Manipulating state in React

Currently, I am enrolled in Samer Buna's Lynda course titled "Full-Stack JavaScript Development: MongoDB, Node and React." While working on the "Naming Contests" application, I encountered a piece of code within the App component that has left me puzz ...

Excessive notification events are currently causing a blockage in the Angular app

Currently, I am utilizing Angular 7 in combination with SignalR on the backend for push notifications. At certain times, an overwhelming amount of notifications flood in, causing my application to become completely unresponsive. The SignalR service compon ...

HTML tag data search using Regex

I received an HTTP request and I'm attempting to extract specific data from it using a regular expression. For instance, in this particular part of the HTML: <tr><th>Continent:</th><td class='trc'>Europe (EU)</td& ...

What is the best way to include CSS in a CodeIgniter project?

I am facing an issue with loading a CSS file in Codeigniter. It seems like there might be something wrong with my code. Can someone help me understand how to properly load a CSS file in Codeigniter and possibly identify any errors in my current code? < ...

Angular.js has been activated with the chosen:open event

I've been implementing the chosen directive for AngularJS from this source and so far it's performing admirably. However, my goal is to trigger the chosen:open event in order to programmatically open the dropdown menu as outlined in the chosen do ...

Using $.getJSON is not functioning properly, but including the JSON object directly within the script is effective

I'm currently working on dynamically creating a simple select element where an object's property serves as the option, based on specific constraints. Everything is functioning properly when my JSON data is part of the script. FIDDLE The follow ...

Is there an easy method to verify if the local storage is devoid of any data?

Query is named aptly; seeking to verify in a conditional statement. ...

Bootstrap Modal closing problem

While working on a bootstrap modal, I encountered an issue where the modal contains two buttons - one for printing the content and another for closing the modal. Here is the code snippet for the modal in my aspx page: <div class="modal fade" id="myMod ...

"Encountering an issue where the route function in Passport and ExpressJS is not being

When using passport for admin authentication, I am facing an issue where the redirect is not calling my function. Consequently, all that gets printed on login is [object Object] Here is my code: app.get('/admin', isLoggedIn, Routes.admin); ...

Issues with Select2 Ajax functionality not functioning as intended

I am currently using the select2 library to create a dropdown menu with ajax functionality, but I am encountering some issues. Below is my code: $("#guests").select2({ multiple: true, minimumInputLength: 1, formatInputTooShort: fun ...

Seeking help with h2 headings, nested hyperlinks, and clickable images

Attempting to tackle a homework question today. This is the task at hand.... List a variety of foods in the following categories: Sandwiches, Drinks, Desserts. Use h2 tags to create these categories. Under each category, create a nested list that inc ...

The conflict between Material UI's CSSBaseline and react-mentions is causing issues

Wondering why the CSSBaseline of Material UI is causing issues with the background color alignment of React-mentions and seeking a solution (https://www.npmjs.com/package/react-mentions) Check out this setup: https://codesandbox.io/s/frosty-wildflower-21w ...

Updating controller variables when the route changes in AngularJS

I'm new to the AngularJS scene and I've encountered a challenge. My goal is to have the selected tab change dynamically based on the URL changes. Here's my JavaScript code: app.config(function($routeProvider, $locationProvider){ $rou ...

How to perfectly align squares in CSS Grid

I'm working on arranging four squares in a grid pattern, two on top and two on the bottom, with equal spacing between them. Currently, the squares shift based on the fr value in CSS grid, resulting in uneven spacing like this: I want to align all fou ...

mysql nodejs function is returning a null value

Kindly review the contents of the dbfn.js file /*This is the database function file*/ var db = require('./connection'); function checkConnection(){ if(db){ console.log('We are connected to the Database server'.bgGreen); ...

The function Event.preventDefault seems ineffective when attempting to block input of CJK (Korean) characters in a v-text-field of type

Currently, I am tackling an issue in a Vue project where I need to fix a small bug. However, the solution seems quite challenging. I have managed to make the v-text-field accept only numerical input, which is functioning well. <v-text-field type=" ...

Initiating an AJAX request to communicate with a Node.js server

Recently, I started exploring NodeJS and decided to utilize the npm spotcrime package for retrieving crime data based on user input location through an ajax call triggered by a button click. The npm documentation provides the following code snippet for usi ...

My JavaScript functions are not compliant with the HTML5 required tag

I am currently developing input fields using javascript/jQuery, but I am facing an issue with the required attribute not functioning as expected. The form keeps submitting without displaying any message about the unfilled input field. I also use Bootstrap ...