I am interested in developing a select box with autocomplete functionality

Here is the HTML code I have:

<select class="form-control" id="city" style="width:100%; margin-left:2%;">
        <option>Sonal</option>
        <option>abcd</option>
        <option>3</option>
        <option>4</option>
        <option>aaaa</option>
    </select>

What I am looking for: I want to select "abcd". There are two ways of selecting it.

  • First, click on the dropdown and select one option.
  • Secondly, type a key in the select box and related answers will be filtered.

    For example, if we type 'a' in the select box, then two options should filter in the dropdown.

    1. abcd 2. aaaa

Answer №1

Check out these example fiddles

Example fiddle 1 and also this Example Fiddle 2

The concept is to update the values in the select list with the option that contains the filter text.

$('<option>').text(option.text).val(option.value).attr('rel', option.rel)

Sources

Answer №2

If you're looking for a solution with maximum flexibility, consider utilizing the jQuery Autocomplete feature.

Answer №3

It seems like the solution to your issue involves using a <datalist> control.

Check out this example from W3 for reference:

http://www.example.com

The <datalist> is a combination of an input field and a dropdown menu where users can type in entries and the dropdown options are filtered accordingly.

Answer №4

/*This is a customizable editable dropdown selection, designed to control all editable selections on an HTML or PHP page */  

//html
<input type="text"  name="machine" id="machinein" syze="30"/>
<input type="button" class="btnselect" id="machine" value="v"/>
<div class="select" id="machinediv">
    <div class="suggest-element" id="item1">Item 1</div>
    <div class="suggest-element" id="item2">Item 2</div>
    <div class="suggest-element" id="item3">Item 3</div>
    <div class="suggest-element" id="item4">Item 4</div>

</div>

//css

        .suggest-element{
            margin-left:5px;
            cursor:pointer;
        }
        .select {
            position:absolute;
            z-index: 100;
            width:350px;
            border:1px solid black;
            display:none;
            background-color: white;
        }

//javascript-jquery

$('.btnselect').click(function(){

    //get input and div
    var inp = $(this).attr('id')+"in";
    var div = $(this).attr('id')+"div";

    //show the div
    document.getElementById(div).style.display = 'block';

    //click in select
    $('.suggest-element').click(function(){
        //get id of the click element
        var id = $(this).attr('id');
        //Edit the input with the click element data
        document.getElementById(inp).value=id;
        //hide the div
        document.getElementById(div).style.display = 'none';
     });

 });

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

Customize your jQuery 3.x version by adding Ajax functionality tailored to your

I've been working on creating a custom jQuery 3.x version, but I'm facing the issue of maintaining the functionality of $.ajax even when ajax is not explicitly removed. Below are my build and grunt settings: grunt custom:-css/showHide,-deprecate ...

The navigation bar is positioned at the forefront, blocking any elements from being displayed beneath it

I just started using Bootstrap and I'm facing an issue with my navbar. No matter what I do, anything I place goes behind it. Even with margins and the native padding from Bootstrap, I can't get the distance right because the div that I want to mo ...

I am hoping for JavaScript to perform three distinct actions depending on the names of the files that are currently open in Photoshop

Currently, I am in the process of developing a JavaScript script for Photoshop. The main objective of this script is to prompt the user to choose a folder containing multiple files. Subsequently, the script will open each file within the folder and perform ...

How AngularFire automatically adds back a removed item in a Firebase array

I have been working on a way to remove an item from my $firebaseArray called "boxes". Here is the "remove" function: function remove(boxJson) { return boxes.$remove(boxJson); } Although it gets removed, I noticed that it immediately reappea ...

Animating the height of a div using nested div elements

Below is the code snippet provided: https://jsfiddle.net/wc48jvgt/69/ The situation involves a div with a horizontal layout named #cleaning_card_1, containing embedded divs that act as borders, and a vertical div called #cleaning_card_right_1 with a neste ...

Tips for resolving the error: finding the right loader for handling specific file types in React hooks

data = [{ img: '01d' }, { img: '02d' }] data && data.map((item) => ( <img src={require(`./icons/${item['img']}.svg`).default} /> )) I am facing an issue with the message Error: Module parse failed: U ...

The parameter type 'Event' cannot be assigned to the argument type

edit-category-component.html: <custom-form-category *ngIf="model" [model]="model" (onSaveChanges)="handleChanges($event)"></custom-form-category> <mat-loader *ngIf="!model"></mat-loader> edi ...

What is the best way to delete a subdocument from a main document when either condition x is true or condition y is true?

A subdocument referred to as Bets is embedded into an array of a property on another model called Users. When a user removes a friend, all associated bets with that specific user should also be deleted from the User document (the user who was friends with ...

jQuery: Enhancing window size change function for unique scenarios

I am looking to place my footer directly below the navigation bar when the window size is less than 1000px in width and less than 500px in height. For the most part, it is functioning as intended based on my code. However: The issue arises when the window ...

Determine in JavaScript whether an array includes a function in its elements

Currently, I am adding anonymous functions to an array in the following manner: myArray.push(function(){ /* some unique code here */}); myArray.push(function(){ /* even more unique code here */}); Afterwards, I execute all the functions by doing while ( ...

Comparison between triggering a 'click' event with or without indexing is often debated in web development circles. While trigger('click') invokes the click event

Can someone clarify the difference between using trigger('click') and trigger('click')[0]? Are there any distinctions between the two? ...

Can someone help me figure out how to trigger my function after my jQuery 'each' function has completed along with all the AJAX calls it includes?

Hello all, seeking some guidance here. I have experimented with various solutions from SO and other sources. This particular one caught my attention as I tried to ensure that my function wouldn't execute until all ajax calls were completed. However, I ...

arranging a collection of images based on their values in increasing order

cardShop is a container with various images, each with its own unique ID and value attribute. These values consist of two numbers separated by a comma, such as 2000,500 or 1500,200. My goal is to sort these images in ascending order based on the first numb ...

influence the order in which dom elements are loaded when the site is loaded

I am seeking advice on how to control the loading sequence of elements in my website. The issue I am facing involves a curtain effect (a <div> with a background-image) overlaying my site, which triggers an animation function to remove it once the pag ...

Obtain the identification numbers from the row within the table

I have a table displaying an email Inbox (see excerpt screenshot here). When the user clicks on a checkbox, I need to populate two dropdowns with the correct items. function fnHandleSelectCBClick(cb) { try { var tableRow = $(cb).parent().par ...

Solving the puzzle of complex polymorphic object model deserialization in Java Jackson: Facing the JsonMappingException error – Unexpected token (START_OBJECT) instead

I am working with a hierarchy of objects described as follows: A B extends A C extends B D extends B E extends C F extends A and contains a reference to A The annotation for class A is defined as: @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS,include=Jso ...

Removing script tags and css links from ajax response while filtering out any extraneous information

Is there a way to eliminate the <script> tags from the ajax response I'm receiving? The server is sending back a json encoded array that contains some unwanted <script> tags (which are being generated by my application and cannot be remove ...

Setting the width of colspan elements can be challenging when other columns have dynamic widths

I am working with a table setup that includes various columns for data tracking: <table > <thead style="width: calc(100% - 15px); display: table; table-layout: fixed;"> <tr> <th colspan="3">& ...

Is there a way to use jQuery to toggle a child element when the parent is clicked?

There are three images displayed on a webpage, each accompanied by a list of three events. The desired functionality is that when a user clicks on an event, the corresponding information should be displayed below that event. Below is the HTML structure: & ...

Is there a way to connect a function to a div using anchor tags that mimic a dropdown menu?

Here is the HTML code for a navigation bar that I have created <div class="navbar"> <a href="#home">Home</a> <div class="dropdown"> <button class="dropbtn">Categories ...