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

AngularJS: dependent dropdown menus

Attempting to create a cascade dropdown in Angular, I assumed it would work seamlessly with binding. Here is the code snippet: <select name="client" ng-model="selectedRequest.client" ng-options="c.name for c in clients track by c.id" req ...

The functionality of the typeof operator is not behaving as anticipated

I am currently working on a script to verify the existence of a specific JavaScript object. var success = function(data) { var x= 0; var numOfCards = data.length; for (x=0;x<data.length - 1;x++) { if (typeof data[x].l ...

Utilize Cordova to download files and access them within the Cordova framework

Apologies for my lack of knowledge, any guidance or assistance in the right direction would be highly valued. I am working on a small application that retrieves data from an API using json requests. One of the functionalities required is to download a spe ...

Using vue-resource to intercept an ajax error and catching the "Uncaught (in promise)" exception

I am utilizing vue-resource to retrieve data from the server. In order to access the correct data, a user must possess a JWT token. If the token is invalid or has expired, a status code of 401 will be returned. Similarly, if a user attempts to reach a forb ...

Unable to generate this QUIZ (JavaScript, HTML)

Hi there, I'm working on a sample quiz and having trouble displaying the result. As a coding newbie, I could really use some help. In this quiz, users answer questions and based on their responses, I want to display whether they are conservative, agg ...

Web Scraping - Is there anyone who can help tidy this up?

I've been grappling with this web scraping project for days now, and as a newbie in this field, I find myself stuck on a crucial issue that I can't seem to resolve. My Challenges The problem lies in the span loop location - currently it prints ...

String values should determine whether a checkbox is checked or not

When retrieving data from LocalStorage, my code looks like this: angular.module('madMeApp').controller('campaignInDetails', function($scope) { var campaignToShow = JSON.parse(localStorage.getItem("CampaignDetails")); $scope.selecte ...

Bootstrap-4 modal not appearing when activated within a dropdown menu

When I tried to use a dropdown feature in my application, I encountered an issue where one of the dropdown items was supposed to open a modal but it wasn't showing up. However, the modal worked perfectly fine when I accessed it using a normal button i ...

Header Dropdown Problems

Hey there, I have a question regarding my header setup. I currently have two headers in place: Whenever I click the notification button, the dropdown menu seems to disrupt the layout of the header. Here is a screenshot for reference: Below is the CSS cod ...

Stylesheets do not have the capability to support template tags

Imagine you have created a stylesheet in Django within the static files and everything is working smoothly. However, when trying to use the following line, an error occurs: .PostProfilePic { width: 50px; height: 50px; border-radius: 50%; background ...

Steps for disabling automatic formatting in Visual Studio Code Version 1.35.1 with system setup

I am currently utilizing visual studio code for my Node JS application with mustache templating. In one of my HTML files, I have the following code: <script> {{{interface}}} </script> After the automatic formatting on save, it appears like t ...

The dilemma of calculating the total width of jQuery's list items

I am in the process of creating a submenu that should look like this: HTML: <ul class="mainMenu clearfix"> <li><a href="#">Eurodan huset</a></li> <li><a href="#">Hustyper</a></li> <li&g ...

Hide the element once the CSS animation has finished

I have successfully implemented an animation using pure CSS that starts on load. However, I am facing an issue with both opacity and visibility as the div continues to take up space even when hidden. Question Is there a way to make the div disappear comp ...

What are the techniques for implementing an if statement in CSS or resolving it through JavaScript?

Demo available at the bottom of the page Within my code, there is a div called #myDiv that defaults to an opacity of 0. Upon hovering over #myDiv, the opacity changes to 1. See the CSS snippet below: #myDiv { opacity: 0; } #myDiv:hover { opacity: 1 ...

Tips for adding a class to the output of a jQuery ajax request?

I've been searching for a solution to this issue without any luck. Below is the code I have: jQuery("#categories_parent_id").change(function() { id = jQuery("#categories_parent_id").val(); jQuery.ajax({ type: ...

utilizing the active class with react js

Apologies for the question, but I am facing an issue where adding an active class to a button is affecting all buttons when clicked. How can this be fixed? Here is the code snippet: <div className=""> {category.items.length === 0 ? ( ...

Utilizing inappropriate HTML attributes

Imagine I have a different layout: <div> <p>My Laptop </p> <p>My Phone </p> </div> With jQuery, if one of these items is clicked, I want to display its value. Would it be acceptable to store extra information in an att ...

What is the reason that setting the margin of 0 on the body does not eliminate the margin on an h1 element?

I believe the body element should apply styles to all elements contained within it. In this scenario, I am attempting to give my h1 element a margin of 0. body { font: 15px/1.5 Arial, Helvetica, sans-serif; padding: 0; margin: 0; background ...

React-beautiful-dnd does not function properly when used with the overflow auto property

Currently, I'm in the process of developing an application similar to "Trello" and have encountered a few challenges along the way. I've successfully created the main components such as the "Board," "Cards," and "Tasks." Each card has a fixed wid ...

Shifting the "active" designation within a dropdown menu to correspond with the user's current page

Recently, I decided to explore the Foundation framework. However, my first stumbling block was figuring out how to use the "active" class in a dropdown menu. I am hoping to have the class applied to the page link that is currently being viewed by the user ...