Searchable dropdown -

Can someone please help me with an issue I am facing? When I try to focus and select from the up and down arrow keys, it is not working as expected.

Below is a snippet of my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8cbddd4dddbcc8af88c9689968895daddccd99689">[email protected]</a>/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1665737a737562245622382738263b747362773827">[email protected]</a>/dist/js/select2.min.js"></script>
    <style>
        .highlight {
            background-color: yellow;
        }
    </style>
</head>
<body>
    <div style="margin-left: 500px; margin-top: 200px;">
        <form action="" method="post">
            <select id='country' name="country" style='width: 200px;'>
                <optgroup label='div1'>
                    <option value='1'>India</option>
                    <option value='2'>America</option> 
                </optgroup>
                <optgroup label='div2'>
                    <option value='3'>Pakistan </option>
                    <option value='4'>Afghanistan</option> 
                </optgroup>
            </select>
            <br/>
            <input type="submit" name="save" value="submit">
        </form>
    </div>

    <script>
        $(document).ready(function(){
            $("#country").select2();

            $("#country").on("select2:open", function (e) {
                // Highlight the initially selected option
                highlightSelected();
            });

            $("#country").on("select2:select", function (e) {
                // Highlight the selected option when selected via mouse
                highlightSelected();
            });

            // Listen for keydown events
            $("#country").on("keydown", function (e) {
                var currentOption = $(this).find(":selected");
                var highlightedOption;

                if (e.which === 38) { // Up arrow
                    highlightedOption = currentOption.prev();
                } else if (e.which === 40) { // Down arrow
                    highlightedOption = currentOption.next();
                }

                if (highlightedOption.length > 0) {
                    $(this).find("option").removeClass("highlight");
                    highlightedOption.addClass("highlight");
                }
            });

            function highlightSelected() {
                var selectedOption = $("#country").find(":selected");
                $("#country").find("option").removeClass("highlight");
                selectedOption.addClass("highlight");
            }
        });
    </script>
</body>
</html>

I have been trying to get the functionality to work where I can use the up and down arrow keys on the keyboard when focusing on elements in the dropdown menu.
...........................................................................................................................................

Answer №1

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3c0d6dfd6d0c781f3879d829d839ed1d6c7d29d82andonanotherthing82">[email protected]</a>/dist/css/select2.min.css" rel="stylesheet" />
    
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91e2f4fdf4f2e5a3d1a5bfa0bfa1bcf3d6c7d20nandonlyinthisoneda0">[email protected]</a>/dist/js/select2.min.js"></script>
    <style>
        .highlight {
            background-color: yellow;
        }
    </style>
</head>
<body>
    <div style="margin-left: 500px; margin-top: 200px;">
        <form action="" method="post">
            <select id='country' name="country" style='width: 200px;'>
                <optgroup label='div1'>
                    <option value='1'>India</option>
                    <option value='2'>America</option> 
                </optgroup>
                <optgroup label='div2'>
                    <option value='3'>Pakistan </option>
                    <option value='4'>Afghanistan</option> 
                </optgroup>
            </select>
            <br/>
            <input type="submit" name="save" value="submit">
        </form>
    </div>

    <script>
        $(document).ready(function(){
            $("#country").select2();

            $("#country").on("select2:open", function (e) {
                highlightSelected();
            });

            $("#country").on("select2:select", function (e) {
                highlightSelected();
            });

            $("#country").on("select2:selecting", function (e) {

                $("#country").find("option").removeClass("highlight");
            });

            function highlightSelected() {

                var selectedOption = $("#country").find(":selected");
                $("#country").find("option").removeClass("highlight");
                selectedOption.addClass("highlight");
            }
        });
    </script>
</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

Dynamic Cascading Selection

I am new to using JQuery Ajax and I need help with creating a PHP script to read the subcategory list based on the selected main category. I have implemented a jQuery AJAX function in my asset_add.php file. <script src="jquery.min.js"></script> ...

Showing concealed information through JQuery Datatables

I am currently working on a project where I need to use datatables to display information extracted from a database. The first part, which involves displaying some of the information, is already working perfectly. However, I am facing difficulties with the ...

What is the best way to add the current date to a database?

code: <?php session_start(); if(isset($_POST['enq'])) { extract($_POST); $query = mysqli_query($link, "SELECT * FROM enquires2 WHERE email = '".$email. "'"); if(mysqli_num_rows($query) > 0) { echo '<script&g ...

Retrieving Basic HTML Source Code in UITextView Without CSS Styling Using Objective-C

I am looking to make changes to HTML text within a UITextView. The original text was created using an HTML editor in the web version of the app and needs to be edited with a default font on iOS. Here is the simple HTML code for the text that needs editing ...

Persist the current scroll position of a div in local storage using React

Despite the numerous questions I've come across on this topic, none of them align with my approach. Most solutions involve window scrolling, but I have a div containing overflow items that I want to retain the user's scroll position for. My attem ...

Adjust the size of an image instead of formatting text to fit around it when the browser window is resized

Is there a way to make an image scale down instead of having text wrap around it when the browser window is resized to be more narrow? Currently, the text wraps under the image before the image scales due to its max-width property. The desired outcome is ...

Angular textbox with dynamic concatenated name functionality

Hello, I'm currently working with some code that looks like this: <div *ngFor="let phone of phoneList; let phIndx = index;"> <div class="peoplePhoneTxtDiv"> <input [disabled]="phone.disabled" class="peoplePhoneTxtBox" type="text" ...

AngularJS fails to activate an event that is managed by addEventListener

I am currently attempting to activate an event on an <A> element using the mousedown event handled by a addEventListener call. However, I am puzzled as to why it is not functioning as expected. I attempted to utilize angular.element(el).triggerHand ...

Model-View-Controller - Utilize AJAX to upload a document

I've encountered an issue with uploading documents using Ajax in my code. When I check for Request.Files.Count, it always returns 0, preventing the file from being uploaded. Here is a snippet of the front-end code: <input type="file" name="na ...

A guide on displaying an Angular Component within a Thymeleaf page

Currently, I am faced with the task of integrating Angular and Thymeleaf. This is necessary because I have developed a dynamic graph using Angular and now need to incorporate it into an existing project that utilizes Thymeleaf. Are there any simplified m ...

The ng-tagsInput feature seems to be malfunctioning

JavaScript var app = angular.module('plunker', ['ngTagsInput']); //'ngTagsInput' app.controller('MainCtrl', function($scope, $http) { $scope.tags = []; $scope.loadTags = function(query) { return $http.get( ...

Revising input form following table update with jquery or ajax

Recently, I created a table using jQuery and Ajax after watching some tutorials. Although I am not an advanced programmer, I managed to insert values into the table. Now, my challenge is to calculate the sum of these values in an input field without having ...

Image showcasing the background

I'm facing an issue with adding a background image to my project Even after trying to add it globally, the background image is not showing up on the Next.js index page. import { Inter } from 'next/font/google' const inter = Inter({ subsets: ...

What goes on behind the scenes of Angular interpolation with scripts?

I set up a variable called test = '<script>alert()</script>'. I then inserted this variable into an Angular component using interpolation like so: <div>{{ this.test }}</div>. However, instead of rendering properly, it just ...

Error message: "jQuery DataTables not working - table disappears when modal window opens

Currently working on an asp.net mvc application that utilizes the datatables grid. The grid is displayed and I have added a rowclick event to it: function CreateRowClickHandler() { var table = $('#table').dataTable(); $("#table > tbody").on(& ...

Pseudo-class for clicking a button on Mobile WebKit

Currently, I am in the process of developing a private framework to replicate the iOS UI using CSS 3 and HTML 5. Most of the widgets have been created, including various colored gradient buttons, but faced with challenges when attempting to incorporate a b ...

Animations with the -webkit- prefix

I recently came across some CSS code that used the -webkit- prefix inside both @keyframes and @-0webkit-keyframes. This was part of a project called animate.css Do you think this is necessary? ...

Retrieving an image from a JSON file based on its corresponding URL

I am trying to extract the URL and display it as an image: This is how it appears in JSON: https://i.sstatic.net/vpxPK.png This is my HTML code: <ul> <li *ngFor="let product of store.Products"> <p>Product Image: {{ product.Pr ...

How can we have a div stay at the top of the screen when scrolling down, but return to its original position when scrolling back up?

By utilizing this code, a div with position: absolute (top: 46px) on a page will become fixed to the top of the page (top: 0px) once the user scrolls to a certain point (the distance from the div to the top of the page). $(window).scroll(function (e) { ...

Saving incoming text files from a client via a websocket connection: A step-by-step guide

I've been working on creating a websocket server in node.js from scratch, without relying on any frameworks. So far, I have successfully set up the messages to be sent from the client to the server. However, I recently encountered an issue when trying ...