Is it possible for a search box selection toggle to reveal a hidden information box underneath it containing all the compiled data?

Improve the user experience on my website by implementing a search feature for US states and Canadian territories. When visitors type in their selection, I want them to be able to click on an icon that will reveal relevant information about that choice.

This example, originally from CodeNepal but customized by me, demonstrates what I'm looking for. Instead of redirecting users to a Google search page, I want a specific box to expand below the searchbox when they make a selection. I understand that the "weblink" line needs to be modified to achieve this functionality, but I'm unsure of how to adjust it to show/hide a div element or something similar.

Note: Rather than linking each selection to a database entry, I plan to manually code each one into separate div elements with anchors.

 <div class="wrapper">
   <div class="search-input">
     <a href="" target="_blank" hidden></a>
     <input type="text" placeholder="Type to search..">
     <div class="autocom-box"gt;
       <!-- data list inserted dynamically using JavaScript -->
     </div>
     <div class="icon"><i class="fas fa-search"></i></div>
   </div>
 </div>


<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}

body{
  background: #644bff;
  padding: 0 20px;
}

::selection{
  color: #fff;
  background: #664AFF;
}

.wrapper{
  max-width: 450px;
  margin: 150px auto;
}

.wrapper .search-input{
  background: #fff;
  width: 100%;
  border-radius: 5px;
  position: relative;
  box-shadow: 0px 1px 5px 3px rgba(0,0,0,0.12);
}

.search-input input{
  height: 55px;
  width: 100%;
  outline: none;
  border: none;
  border-radius: 5px;
  padding: 0 60px 0 20px;
  font-size: 18px;
  box-shadow: 0px 1px 5px rgba(0,0,0,0.1);
}

.search-input.active input{
  border-radius: 5px 5px 0 0;
}

.search-input .autocom-box{
  padding: 0;
  opacity: 0;
  pointer-events: none;
  max-height: 280px;
  overflow-y: auto;
}

.search-input.active .autocom-box{
  padding: 10px 8px;
  opacity: 1;
  pointer-events: auto;
}

.autocom-box li{
  list-style: none;
  padding: 8px 12px;
  display: none;
  width: 100%;
  cursor: default;
  border-radius: 3px;
}

.search-input.active .autocom-box li{
  display: block;
}
.autocom-box li:hover{
  background: #efefef;
}

.search-input .icon{
  position: absolute;
  right: 0px;
  top: 0px;
  height: 55px;
  width: 55px;
  text-align: center;
  line-height: 55px;
  font-size: 20px;
  color: #644bff;
  cursor: pointer;
}
let suggestions = [
    "Alabama",
    "Alaska",
    "Arizona",
    "Arkansas",
    "California",
    "Colorado",
    "Connecticut",
    "District of Columbia",
    "Delaware",
    "Florida",
    "Hawaii",
    "Idaho",
    "Illinois",
    "Indianar",
    "Iowa",
    "Kansas",
    "Kentucky",
    "Louisiana",
    "Maine",
    "Maryland",
    "Massachusetts",
    "Michigan",
    "Minnesota",
    "Mississippi",
    "Missouri",
    "Montana",
];


// getting all required elements
const searchWrapper = document.querySelector(".search-input");
const inputBox = searchWrapper.querySelector("input");
const suggBox = searchWrapper.querySelector(".autocom-box");
const icon = searchWrapper.querySelector(".icon");
let linkTag = searchWrapper.querySelector("a");
let webLink;

// if user press any key and release
inputBox.onkeyup = (e)=>{
    let userData = e.target.value; //user enetered data
    let emptyArray = [];
    if(userData){
        icon.onclick = ()=>{
            webLink = `https://www.google.com/search?q=${userData}`;
            linkTag.setAttribute("href", webLink);
            linkTag.click();
        }
        emptyArray = suggestions.filter((data)=>{
            //filtering array value and user characters to lowercase and return only those words which are start with user enetered chars
            return data.toLocaleLowerCase().startsWith(userData.toLocaleLowerCase());
        });
        emptyArray = emptyArray.map((data)=>{
            // passing return data inside li tag
            return data = `<li>${data}</li>`;
        });
        searchWrapper.classList.add("active"); //show autocomplete box
        showSuggestions(emptyArray);
        let allList = suggBox.querySelectorAll("li");
        for (let i = 0; i < allList.length; i++) {
            //adding onclick attribute in all li tag
            allList[i].setAttribute("onclick", "select(this)");
        }
    }else{
        searchWrapper.classList.remove("active"); //hide autocomplete box
    }
}

function select(element){
    let selectData = element.textContent;
    inputBox.value = selectData;
    icon.onclick = ()=>{
        webLink = `https://www.google.com/search?q=${selectData}`;
        linkTag.setAttribute("href", webLink);
        linkTag.click();
    }
    searchWrapper.classList.remove("active");
}

function showSuggestions(list){
    let listData;
    if(!list.length){
        userValue = inputBox.value;
        listData = `<li>${userValue}</li>`;
    }else{
      listData = list.join('');
    }
    suggBox.innerHTML = listData;
}

Answer №1

Custom Dropdown List with Search Capability

// Array of state names for dropdown menu
let statesList = [
  "Alabama",
  "Alaska",
  "Arizona",
  "Arkansas",
  "California",
  "Colorado",
  "Connecticut",
  "District of Columbia",
  "Delaware",
  "Florida",
  "Hawaii",
  "Idaho",
  "Illinois",
  "Indianar",
  "Iowa",
  "Kansas",
  "Kentucky",
  "Louisiana",
  "Maine",
  "Maryland",
  "Massachusetts",
  "Michigan",
  "Minnesota",
  "Mississippi",
  "Missouri",
  "Montana",
];
const dropdownList = document.getElementById('statesList');

// Populate the dropdown list with state options
statesList.forEach((state, index) => {
  let optionElement = document.createElement("option");
  optionElement.label = state;
  optionElement.value = state;
  optionElement.id = state;
  dropdownList.appendChild(optionElement);
});

const searchSelectedState = () => {
  const selectedOption = document.getElementById('states').value;
  console.log(selectedOption);
  // Perform actions based on the selected state
}
<html>
<body>
<h1>Custom Dropdown List with Search Capability</h1>
<form>
    <label for="states">Choose your state:</label>
    <input list="statesList" id="states" name="states" placeholder="Start typing..." />
  <button type='button' onclick='searchSelectedState()'>SEARCH</button>
    <datalist id="statesList"></datalist>
</form>
</body>
</html>

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

Is there a way to prevent the window.status from appearing?

I currently have the following code snippet: <a class="button accessLink" id="loginLink" href="#" data-action="Login" data-dialog="access" data-disabled="false" data-entity="n/a" ...

Click the 'expand' button for additional details on every row in the table

I am facing a challenge with my HTML table where I have a lot of information to add for each row. However, displaying everything at once makes the page look cluttered. Therefore, I am looking to add a "view more" button in another column for each row. Des ...

Encountering difficulties in accessing state while utilizing async callback functions in React.js

After finding this function on Stack Overflow, I decided to use it in order to update a database and profile information immediately after a user signs up. The function is working as expected, but I am encountering an issue where I can no longer access the ...

Having trouble installing node-sass through npm

Currently, I am attempting to install the SASS compiler node-sass in order to compile SCSS code into CSS code. Despite following an online tutorial and replicating the same steps, I keep encountering errors. npm init --yes : this will generate a json file ...

Encountering a jQuery error while trying to utilize the $window.load

I have a code snippet that is functioning well when wrapped within a document ready event: jQuery(document).ready(function($) { $('tr[data-name="background_colour"] input.wp-color-picker').each(function() { //this section works fin ...

Occurrences repeating several times following the incorporation of fresh content into the DOM

I am facing an issue with my plugin. I have implemented an update method to handle new elements added to the DOM. Initially, everything works perfectly without any errors or issues. However, when a new element (div with class "box") is added to the DOM, th ...

What is the reason why setting 'onClick' as an event handler is not flagged as a syntax error?

I am currently working on a JavaScript code snippet where I am trying to change the headline text when it is clicked. The code I have written is: var headline = document.getElementById("mainHeading"); headline.onClick = function() { headline.innerHTML ...

Having difficulty retrieving items from Mongoose-Node database

I am currently working with a Mongodb database that stores resume objects. These objects contain various skills information and I have set up a node-express server to query the database based on specific skills. For example, when querying for a skill like ...

Creating a simple Node.js project using material web components - a step-by-step guide

I have recently started experimenting with Node.js. This is a basic program I created to test the integration of material-components-web. I followed the instructions provided in the readme file and here's what I have implemented so far: package.json ...

Creating Angular Custom Form Validation and Custom Directives

I recently created a custom validation directive and applied it to the form element like this: <form myValidations> app.directive('myValidations', function(){ return{ //require: 'ngModel', note its commented out link: f ...

NextJS will redirect the user back to the previous router they came from following authentication

Hello! I am currently facing a challenge in redirecting a user back to the initial page they clicked on after being authenticated. The issue lies in server-side rendering (SSR) and the lack of access to the window.history object in getServerSideProps. The ...

Creating a Vue component using v-for and a factory function allows for dynamic

I am currently developing a Table component using factory functions for all logic implementation. Within a v-for loop, I generate a cell for each item in every row. The factory Below are the actual factories that I import into the respective vue page whe ...

Adjust the width of the table by utilizing the border-collapse property set to collapse

I am completely baffled by this situation. Whenever I adjust the border-width of a table (either dynamically with JavaScript or in Chrome Dev Tools) where border-collapse: collapse; is set, transitioning from a border width of 1px (#1) to a larger value (# ...

When importing data from a jQuery AJAX load, the system inadvertently generates duplicate div tags

Currently, I am utilizing a script that fetches data from another page and imports it into the current page by using the .load() ajax function. Here is the important line of code: $('#content').load(toLoad,'',showNewContent()) The issu ...

The resend email feature isn't functioning properly on the production environment with next js, however, it works seamlessly in the development environment

import { EmailTemplate } from "@/components/email-template"; import { Resend } from "resend"; const resend = new Resend("myApiKey"); // this works only in dev // const resend = new Resend(process.env.NEXT_PUBLIC_RESEND_API_KE ...

Puppeteer throwing an error when querying selectors cannot be done (TypeError: selector.startsWith is not a supported function)

I recently installed Puppeteer and ran into an issue when trying to query a selector. I keep receiving a TypeError: selector.startsWith is not a function error. I attempted to resolve the problem by tweaking the core code and adding toString(), but unfort ...

suggestions for customizing Angular Material

The guidelines regarding materials specify that: "For any Angular Material component, you are allowed to define custom CSS for the component's host element that impacts its positioning or layout, such as margin, position, top, left, transform, and z- ...

Filtering Tables with AngularJS

Currently, I'm experimenting with using angularJS to filter data in a table. My goal is to load the data from a JSON file that has a structure like this (example file): [{name: "Moroni", age: 50}, {name: "Tiancum", age: 43}, { ...

Troubleshooting: jQuery AJAX failing to receive JSON data in HTTP request

Experimenting with HTML and jQuery to practice JSON requests, I conducted some research and attempted a small test. However, upon running the script in Google Chrome, only my HTML/CSS elements appeared instead of expected results. Below is the code snippet ...

Executing javascript href using Python in Selenium

Currently, I am attempting to use Selenium in Python to click on a href JavaScript link. The HTML code appears as follows: HTML Example and my goal is to click on javascript:goType(1). This is the approach I have taken: advance_search = browser.find_el ...