Input the content of a list item element into a text input field

Retrieving data from mySql is a simple task, but once I have the list of items, I've been struggling to create a function that allows clicking on any item in the list to send the text up to the value of the input field. Here's what I've come up with after several days of effort.

// Function to request city data 
function searchCities(str) {
  var responses = document.getElementById('suggestions');
  if (str.length == 0) {
    responses.innerHTML = "";
    responses.setAttribute("style", "display:none;border:none;outline:none;");
    return;
  } else {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        responses.innerHTML = this.responseText;
        responses.setAttribute("style","display: block;border-top: 1px solid #272C33;border-radius: 0 0 4px 4px;padding: 10px;");
      }
    };
    xmlhttp.open("GET", "/editor/queries/cities.php?city=" + str, true);
    xmlhttp.send();
  }

}

// Attempting to send the content to an input field

var items = document.querySelectorAll("#suggestions li");
  for(var i = 0; i < items.length; i++ )
  {
    items[i].onclick = function(){
    document.getElementById('inputField').value = this.innerHTML;
    };
  }

This involves two html elements in the dynamic process:

<input type="search" class="searchBox" name="city" id="inputField" placeholder="Enter destination name" onkeyup="searchCities(this.value)" for="suggestions">

<ul id="suggestions" class="suggestions">
</ul>

Here is the structure of the query:

$city = htmlentities( $_GET['city'], ENT_COMPAT, 'UTF-8' );
$query     = $dcon
  ->query( "
    SELECT *
    FROM cities
    WHERE city LIKE '%$city%'
    ORDER BY city
    ASC LIMIT 10" );

 while ( $result = $query->fetch() )
 {
    echo $cityOutput = '<li>' . $result['city'] . ', ' . $result['state']. ", " . $result['country'] . '</li>';
 }

Could it be that the function isn't working because it requires a pre-existing list to load? And if so... HOW?

Answer №1

The issue encountered stemmed from the querySelector being executed before the list was populated.

To resolve this, I made the decision to place the querySelector within the onreadystatechange function following the response itself. Here is how it was implemented...

    // AJAX Request to cities database
    function searchCities(str) {
      var responses = document.getElementById('suggestions');
      if (str.length == 0) {
        responses.innerHTML = "";
        responses.setAttribute("style", "display:none;border:none;outline:none;");
        return;
      } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            responses.innerHTML = this.responseText;
            responses.setAttribute("style","display: block;border-top: 1px solid #272C33;border-radius: 0 0 4px 4px;padding: 10px;");


         // Newly added querySelector ------------------

          var items = document.querySelectorAll("#suggestions li");
            for(var i = 0; i < items.length; i++ )
            {
              items[i].onclick = function(){
              document.getElementById('citymx').value = this.innerHTML;
              };
            }

         // End of inclusion --------------------------------------

          }
        };
        xmlhttp.open("GET", "/editor/queries/countries.php?city=" + str, true);
        xmlhttp.send();
      }

    }

If there are any corrections needed, please provide feedback in the comments section.

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

Angular select automatically saves the selected option when navigating between views

I would like the selected option in my dropdown menu to stay selected as I navigate through different views and then return back. Here is the view: <select ng-model="selectedSeason" class="form-control" ng-options="season as 'Season '+ seas ...

Having trouble with submitting a form through Ajax on Rails 4

Having models for advertisement and messages with forms that both utilize Ajax (remote => true) for submission. The message form submits perfectly, remains on the same page, and handles the response efficiently. However, the advertisement form fails to ...

Cycle through matching elements for managing unique slick carousels

My experience with using slick carousel and custom pagination has been positive so far. However, I'm now faced with the challenge of incorporating multiple carousels on a single page. While I have come across solutions, implementing them alongside my ...

Can you include conditional logic within a switch statement?

I've been using if, else if, and else statements in my code but recently switched to switch statements which have made things much simpler. Now I'm wondering if it's possible to add multiple conditions inside a switch statement, similar to i ...

Optimizing event mapping with the jQuery "on" function

CODE I: $searchBoxParent.on({ mouseover: function() { $this = $(this); $this.parent().find(".hlight").removeClass('hlight'); $this.addClass("hlight"); }, mouseout: function() { $this = $(this); ...

Using a JavaScript variable to be displayed in a PHP code

Can someone please help me troubleshoot this code? I am attempting to display a JavaScript variable in PHP after applying a regex, but I keep getting the error Uncaught TypeError: document.getElementById(...).html is not a function $.post('display.ph ...

Populate Jquery datatables programmatically

After implementing the Jquery Datatables plugin, I initially had hardcoded content in the table. However, I made some modifications to dynamically populate the table with fetched data. While this change worked fine, I encountered issues with the search f ...

Utilize SocketIO in a separate file

I'm facing a challenge in sending data to all the connected sockets from a different file. Despite my efforts, I haven't been able to crack this problem. Socket.js var socketio = require('socket.io'); var users = require('./modul ...

Incorporate PHP includes or utilize JavaScript AJAX for enhanced functionality

I am currently working on developing an application and I am exploring the most effective method to load JSON files. One option I am contemplating is using PHP include: var jsonFile = <?php echo include "jsonFile.json";?>; var jsonFile_2 = <?php ...

Set up your Typescript project to transpile code from ES6 to ES5 by utilizing Bable

Embarking on a new project, I am eager to implement the Async and Await capabilities recently introduced for TypeScript. Unfortunately, these features are currently only compatible with ES6. Is there a way to configure Visual Studio (2015 Update 1) to co ...

Encountered an unexpected "<" error while using Ajax with MySQL

I am trying to accomplish a simple task - retrieve a table from a MySQL database. Previously, I was using basic MySQL code and it was working fine. However, after switching to MySQLi, I encountered an error: Uncaught SyntaxError: Unexpected token < ...

Error: 'socket' is inaccessible before it has been initialized, specifically in the context of electron

Trying to configure an electron app where a message is sent to the server, and the server places the value on the read-only textarea. However, upon starting the app, the following error appears in the devtools console: Uncaught ReferenceError: Cannot acc ...

Tips on incorporating a changing variable into a JavaScript Shader

I have successfully created a primitive sphere using THREE.SphereGeometry and applied a displacement shader to give it a bumpy effect. My goal now is to animate the scale of the bumps based on input volume from the microphone. Despite my efforts, I am stru ...

Utilizing Jquery to extract a specific string from a URL and fetch a remote element

Recently delving into Jquery, I'm in search of a code snippet that can capture the current page URL and load a remote element if it contains a specific string. For instance: Consider these sample page URLs: "http://......./Country/AU/result-search- ...

Troubleshooting: Google Tag Manager showing a blank page

After attempting to integrate Google Tag Manager into my website, I encountered a strange issue where upon refreshing the page, it would go completely blank with no specific error displayed. I followed the only upvoted solution from a thread on Stack Over ...

Slick Slider isn't compatible with Bootstrap Tab functionality

I'm having an issue with using slick slider within a Bootstrap tab menu. The first tab displays the slick slider correctly, but when I switch to the second tab, only one image is shown. How can I resolve this problem? <!DOCTYPE html> <html ...

Exploring the power of NodeJS 8.x with EventEmitter and the efficiency of async/

Is it possible to use async functions with an event emitter? Some sources advise against it, but I am interested in incorporating async functionality with the event emitter to handle messages. Below is the code snippet I have been working on: server.on(& ...

Problems with Angular functionality

I'm a newbie when it comes to Angular and I'm eager to start practicing some coding. I've put together a simple app, but for some reason, the Angular expression isn't getting evaluated in the browser. When I try to display {{inventory.p ...

Ajax functionality added to save button

I'm in the process of creating an interactive form for clients, and I want to include a submit button that saves their information directly into the database. Is there a method for submitting data via AJAX instead of traditional form submission? ...

What could be causing the axesHelper function to not display the axis on the screen?

I encountered an issue with my code while working with three.js. I am having trouble initializing certain components and objects such as the axis and cube, as they are not displaying on the screen. Can someone please help me identify where the error migh ...