Use JavaScript to dynamically change the value of an HTML input field based on the contents of a <li> list item

On my HTML page, I am dynamically creating <li> elements using an Autocomplete API. As you type in the input box, the API suggests the Website logo, website name, and website URL within the <li> elements. Currently, this functionality is working fine. However, upon clicking on any of the <li> elements, I want to update the input field value with the corresponding website name. For example, if you click on "Linkedin" from the list, the input field should display "Linkedin". This way, I can use this updated value for a POST request later. The list items are appended dynamically using the following code snippet:

$(".results").append('<li data-value="01"><img src="'+item.logo+'">'+item.name+item.domain+'</li>');

$(document).ready(function() {

  $("#suggest").autocomplete({
    minLength: 0,
    delay: 100,
    source: function(request, response) {
      $(".ui-autocomplete").remove();
      // Suggest URL
      var suggestURL = "https://autocomplete.clearbit.com/v1/companies/suggest?query=%QUERY";
      suggestURL = suggestURL.replace('%QUERY', request.term);

      // JSON Request
      $.ajax({
          method: 'GET',
          dataType: 'json',
          jsonCallback: 'jsonCallback',
          url: suggestURL
        })
        .success(function(data) {
          response(data);
          $(".results > li").remove();
          data.forEach(function(item) {
            console.log(item.name, item.logo, item.domain);

            $(".results").append('<li data-value="01"><img src="' + item.logo + '">' + item.name + item.domain + '</li>');
          });

        });
    }
  });

});
body {
  padding: 30px;
}

/* * Copyright (c) 2012 Thibaut Courouble
     * Licensed under the MIT License
       ================================================== */

 ...

</script>

<section class="main">
  <form class="search" method="post" action="index.html">
    <input autocomplete="false" type="text" name="q" placeholder="Search..." id="suggest" value="" />
    <ul class="results">
    </ul>
  </form>
</section>

Answer №1

For better organization, consider adding the item.domain as a data attribute to the <li> tag.

Next, implement a jQuery click event.

Remember, since the data is appended dynamically to your list, attach the click event to the document and include the selector as shown below. Here's an example:

var item = {};

item.domain = 'stackoverflow.com';
item.logo = 'image-url';
item.name = 'stackoverflow';

var x = '<ul><li data-value="01" data-domain="'+item.domain+'"><img src="'+item.logo+'">'+item.name+' '+item.domain+'</li></ul>';

jQuery('.results').html(x);

jQuery(document).on('click', 'li[data-domain]', function(evt){

  var obj = jQuery(this);

  jQuery("#suggest").val(obj.attr('data-domain'));

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="suggest" type="text" value="" />

<div class='results'></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

JavaScript Game Timer

I am working on a countdown timer where I have set the variable seconds to 10. If the seconds reach zero, I want to add 2 seconds to it and stop the program from looping. Can someone please assist me with this? var isWaiting = false; var isRunning = fal ...

JavaScript - An unexpected error occurred: Syntax error, unrecognized expression: [href=#contact] (WordPress)

I am currently working on a feature that involves adding a class to a specific menu item when a certain section is in view. However, I encountered an error that reads: Uncaught Error: Syntax error, unrecognised expression: [href=#contact] Your help would ...

Unable to apply 3rd condition with ngClass into effect

I've been attempting to incorporate a third condition into my ngClass. Initially, I managed to get two classes working in my ngClass to change the row colors alternately. [ngClass]="{ totalrow:i%2 != 0, odd:i%2 == 0}" Now, I'm trying to introdu ...

``So, you're looking to retrieve a collection of objects that have a OneToMany

Is there a way to retrieve a list of objects with a OneToMany relation using TypeORM's queryBuilder? This is the desired output: { "id": 1, "firstName": "Bob", "lastName": "Sparrow", "orders": [ { "id": 1, "name": "Very Big Or ...

Designing an interactive 3D space using JavaScript

I'm currently developing an app that allows users to visualize different wallpapers in a 3D room setting. The concept involves placing the user inside a virtual space with four walls, where they can drag and look around, as well as change wallpapers v ...

An easy way to pass props to a component using useNavigate in React Router

Is it possible to send props directly to a component in React? const goToProjectPage = useNavigate(); useEffect(()=>{ ..... goToProjectPage("/projectpage"); //send props here },[]); ...

Close the gap in the CSS for the image tag

I am facing an issue. Whenever I include an img Tag in my HTML File, there is a Gap around the tag. It is neither margin nor padding. I wonder what it could be? Could someone please assist me in removing the gap with CSS? <img src="../images/modules/ ...

Type Error in Node.js Form Submission: Unable to define 'userId' property due to undefined value

After implementing login and registration features on a specific page in my application at views/employee/login.hbs, I encountered an issue. Upon entering registration details (email, username, password, and confirm password) and clicking the register butt ...

Guide to setting up FullCalendar views based on unique identifiers

Currently, I am working on an MVC project that focuses on tracking vacation days taken by employees. My goal is to display these dates using FullCalendar for each individual employee. At the moment, I can only showcase all employees or none at all, so I am ...

What are some ways to create a table that can be easily filled in?

I'm striving to enhance the user experience by allowing a table cell to be easily editable with just a double click, converting it into an input field with the existing cell value pre-populated. Currently, I have successfully achieved this functional ...

Retrieve the user's unique identification number upon creation and proceed to update the database accordingly

I'm trying to create a cloud function that automatically adds 50 points to the "points" field in the database whenever a new user is created using the "onCreate((user)" function. The goal is to simply detect when a new user is created, retrieve their ...

Encountering difficulties when attempting to run initial React Native app

Struggling with my journey of learning react-native, I encountered a roadblock while trying to run the application. Here is the error log. I'm hopeful for some assistance from anyone who can lend a hand. The development server returned response erro ...

Organizing components within a division

It's maddening... I'm working on a website and trying to create a header div that includes the site name, search bar, and sign in/log in buttons. I want the logo on the left, search bar in the center, and sign in/log in buttons on the right, sta ...

How can I utilize jQuery to iterate through every anchor tag on an HTML page?

I am looking to reference all anchor tags on the page that have a parent h2 tag. To achieve this, I need to iterate through each anchor tag that has a parent h2 and add an attribute using jQuery. <body> <h1>not me</h1> <a href ...

Utilizing the hcSticky plugin for creating a scrolling effect on webpage content

I'm attempting to utilize the JQuery plugin, hcSticky, in order to achieve a scrolling effect on my fixed content. However, I seem to be encountering some difficulty getting it to function properly. What could I possibly be doing incorrectly? JSFIDDL ...

The jQuery.html() method does not extract the input value

I am attempting to dynamically add input fields by taking the current HTML of a div and appending additional HTML code at the end. Here is a snippet of my JavaScript document: jQuery(document).ready(function() { if (jQuery("#services_off ...

Using PHP and JQuery to Implement Cloudinary Callbacks

After uploading images to my cloudinary account, I am unsure where cloudinary is directing the image_id. The documentation mentions that cloudinary_cors.html is supposed to be the destination for Cloudinary's callbacks, but this seems odd as it doesn& ...

"Transforming JSON data into structured key-value pairs using JavaScript

Develop a function named "json_filter" that accepts a JSON-formatted string as input. The accepted format is an array of objects, where each object contains keys for "mass," "density," "temperature," and "velocity," each mapped to a floating-point number. ...

Creating functional links with card-img-overlay in Bootstrap v4

Encountering an issue where Bootstrap v4 cards utilizing card-img-overlay to overlay text on an image are causing links below the image to become unresponsive. The following links are functional: <div class="card" style="border-color: #333;"> & ...

Ways to integrate mouse out functionalities using an if condition

I'm currently working on a menu using Javascript where clicking on one option will dim the other options and reveal a sub-menu. I'm looking to include an if statement in the function so that when a user mouses out of both the sub-menu and the cli ...