Tips for enabling selection of list items in an input tag

Below is the code I have written to create an InputFilter.

MyFilter = function(args) {
    var dataUrl = args.url;
    var divID = args.divID;
    var div = document.getElementById(divID);
    
    var myTable = '<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">' +
        '<ul id="myUL">' + '<li>' + '<a href="#"></a>' + '</li>' + '</ul>';
    div.innerHTML = myTable;

    function foo(callback) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', "data.json", true);
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
                callback(httpRequest.responseText);
            }
        };
        httpRequest.send();
    }

    foo(function(data) {
        debugger;
        var jsonc = JSON.parse(data);
        var new_opt = "";
        for (i = 0; i < jsonc.length; i++) {
            new_opt += '<li><a href="#">' + jsonc[i]['VALUE'] + '</a></li>';
        }
        document.getElementById('myUL').innerHTML = new_opt;

    });

    myFunction = function() {
        debugger;
        var input, filter, ul, li, a, i;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        ul = document.getElementById("myUL");
        li = ul.getElementsByTagName("li");
        for (i = 0; i < li.length; i++) {
            a = li[i].getElementsByTagName("a")[0];
            if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
                li[i].style.display = "";
            } else {
                li[i].style.display = "none";

            }
        }
    }
}

I need help to modify the code so that when a list item is clicked, it gets selected and displayed in the input field like a combo box.

You can find the fiddle version of my code here.

Note : Currently, the code allows searching. I want to implement selection and display functionality as well.

In another project, similar behavior is implemented using a table. The code snippet for that is:

document.querySelectorAll('#myTable tr:not(.header)').forEach(function(_tr) {
    _tr.addEventListener('click', function() {
        document.getElementById('myInput').value += " ; " + this.getElementsByTagName('td')[0].textContent;
    });
});

The goal is to click on items of the a tag and have the selected items displayed in the input tag with ; separation.

Answer №1

Code Playground

function displayResults(input, list) {
    var li, i, match;
    
    for (i = list.children.length; i--; ) {
        li = list.children[i];
        match = li.textContent.toLowerCase().indexOf(input.toLowerCase()) > -1;
        li.classList.toggle('hidden', !match)
    }
}

function updateInputValue(inputElem, value){
inputElem.value = value;
}


var inputElem = document.querySelector('input'),
listItems = document.querySelector("#myList");

inputElem.addEventListener('input', function(e){
displayResults(e.target.value, listItems);
})
listItems.addEventListener('click', function(e){
if( e.target.tagName == 'A' && !e.target.classList.contains('header') )
updateInputValue( inputElem, e.target.textContent )
})
* {
  box-sizing: border-box;
}

input {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myList {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myList li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myList li.hidden{ display:none; }

#myList li a.header {
  background-color: #e2e2e2;
  cursor: default;
}

#myList li a:hover:not(.header) {
  background-color: #eee;
}
<h2>My Directory</h2>

<input placeholder="Search for names.." title="Type in a name">

<ul id="myList">
  <li><a href="#" class="header">A</a></li>
  <li><a href="#">Alice</a></li>
  <li><a href="#">Alex</a></li>

  <li><a href="#" class="header">B</a></li>
  <li><a href="#">Ben</a></li>
  <li><a href="#">Beth</a></li>

  <li><a href="#" class="header">C</a></li>
  <li><a href="#">Charlie</a></li>
  <li><a href="#">Cynthia</a></li>
  <li><a href="#">Chris</a></li>
</ul>

Answer №2

give this a try

With jQuery, you have the ability to automatically populate a text field with a selected name.

function setFieldValue() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName("li");
  for (i = 0; i < li.length; i++) {
    a = li[i].getElementsByTagName("a")[0];
    if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}
$('a').click(function() {
  var val = $(this).text();
  $('#myInput').val(val);
})
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px;
  /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a.header {
  background-color: #e2e2e2;
  cursor: default;
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>My Phonebook</h2>

<input type="text" id="myInput" onkeyup="setFieldValue()" placeholder="Search for names.." title="Type in a name">

<ul id="myUL">
  <li><a href="#" class="header">A</a></li>
  <li><a href="#">Alice</a></li>
  <li><a href="#">Alex</a></li>

  <li><a href="#" class="header">B</a></li>
  <li><a href="#">Blake</a></li>
  <li><a href="#">Ben</a></li>

  <li><a href="#" class="header">C</a></li>
  <li><a href="#">Cameron</a></li>
  <li><a href="#">Claire</a></li>
  <li><a href="#">Chloe</a></li>
</ul>

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

Ar.js results in objects experiencing deformation or modification when manipulated

Recently, I started experimenting with Ar.js and encountered an issue where the objects displayed on the screen seemed distorted. To illustrate this problem, let me share a basic A-Frame example featuring a perfectly round sphere: <!DOCTYPE> <html ...

gulp.watch executes tasks without following a specific sequence

Objective Develop a gulp.watch task to execute other tasks in a specific sequence Why this is unique While many have referred me to How to run Gulp tasks sequentially one after the other, my query differs as it pertains to using gulp.watch instead of gu ...

Tips for creating an expression within ng-if

I am struggling with placing an expression inside ng-if that needs to be assessed in order for my content to be shown based on its outcome. This is what I currently have: <a ng-if="abc.status===failure" href="http://localhost:3000/abc/abc">image< ...

Show a dynamic highchart graph displaying linear data retrieved from the database

I am attempting to present data retrieved from a database in a linear highchart format. Here is the JSON response from my database: [{"protocol":"tcp","date":"01/02/20","time":"00:10:20","total":281}, {"protocol":"udp","date":"01/02/20","time":"00:10:30", ...

What is the best way to align my Navbar in the center?

Previously, I searched on this platform for solutions but couldn't find anything that worked. Currently, I am using the Bulma Framework which is not very well-known. However, I need assistance in aligning the brand link on the navbar to the center. Be ...

How can we activate navigation on a mobile browser?

I am currently working on a small HTML5/JavaScript website designed to be accessed by mobile browsers on devices such as Android and iPhone. I am utilizing the geolocation feature of HTML5 to obtain the user's current location, but my goal is to then ...

Nuxt router directing to incorrect URL upon refreshing the page

Let me show you exactly what I mean by setting up a demo Nuxt blog at https://example.com/nuxtblog/. This demonstration includes articles populated by the @nuxt/content package. The website has been generated statically using the nuxt generate command. Fol ...

Error: An attempt was made to wrap a property called "find" as a function, but it is

I am currently implementing a test-driven development approach to run my tests. I have successfully run the same test on another application by copying and pasting it, but I encountered an error in this particular test: TypeError: Attempted to wrap unde ...

Leverage the Frontend (Headless Commerce) to utilize the Admin API and retrieve products from Shopify

Attempting to retrieve products from Shopify using the Admin API (GraphQL) through my frontend. I utilized the following code: *I implemented "axios" on Quasar Framework, utilizing Headless Commerce const response = await this.$axios({ url: "https: ...

What is the most effective method for incorporating multi-line breadcrumb links in a React application?

I am currently working on implementing a multiline breadcrumb link feature for mobile and tablet devices. As users navigate through multiple folders, I need to handle scenarios where the number of links exceeds the maximum allowed in the breadcrumb contain ...

How can AngularJS handle multiple routes using unique templates while sharing the same controller?

I am currently researching whether I can achieve the functionality described in the title. Here are my initial thoughts: Let's consider the following routes I have set up: .when('/', { templateUrl : 'partials/homepage.html&ap ...

Step-by-step guide on extracting checkbox value from response in Angular JS

Successfully added a checkbox value to the database. An issue arises when checking a checkbox after receiving a response, as the checked value displays as -1 instead of 0, 1, or 2. When clicking on a checked box, its index value should change to -1, bu ...

Attempting to maintain the main navigation highlighted while browsing through the secondary navigation

I am facing a small issue that seems like it should be an easy fix, but I can't seem to figure it out. While working on my site, I'm having trouble keeping the parent navigation highlighted when scrolling through the sub-menu. If you hover over ...

Building a solid foundation for your project with Node.js and RESTful

I need to integrate a legacy system that offers an api with rest/json queries in Delphi. I plan to consume this data and build an app using angular + nodejs. My goal is for my application (client) to only communicate with my web-server on nodejs, which wil ...

How to add additional text after a particular line within a string containing multiple lines using JavaScript

What is the best way to add a new string after line 2 in a multi-line JavaScript string? ...

Troubleshooting Jqgrid Keyboard Navigation Problem

Here is a link to the jsfiddle code snippet. Upon adding jQuery("#grid").jqGrid('sortableRows'); into my JavaScript code, I encountered an issue where keyboard navigation no longer worked after sorting rows Below is the JavaScript code snippet: ...

AngularJS and KendoUI integration experiencing delays during script evaluation

At the moment, I am conducting performance measurements and analysis on our AngularJS-KendoUI application in an effort to identify any bottlenecks. Following a helpful article and an informative presentation, I am using Chrome DevTools timeline tab to anal ...

An issue occurred while trying to establish the referrer policy

I encountered an error in my Chrome console while working on a WordPress site. The following error message showed up: "Failed to set referrer policy: The value 'http://example.com/comic/' is not one of 'always', 'default' ...

Understanding page navigation in PHP

Is there a way to validate the inputs on a given page, display error messages if any, and then move to the next page if the inputs are correct? How can this be achieved? <html> <head></head> <body> <?php // define variables an ...

Completely shrink the middle row first when resizing the browser before shrinking the other rows

Utilizing a simple three row structure: <div class="EditorHeaderWrapper"> <h1>Title</h1> </div> <div class="EditorMainRowWrapper"> // Content of the main row goes here </div> <div class="EditorFooterWrapper"> ...