Developing a customized autosuggest feature using AJAX with comprehensive keyboard accessibility

Has anyone tried building their own AJAX auto suggest text box with full keyboard support?

I've managed to create the auto suggest feature by connecting to a SQL DB and displaying results, but the only way to interact with the search results is through the mouse. I'm looking to be able to navigate up and down with the keyboard, use the enter key to select an item, and be redirected to the relevant page.

I've found plenty of resources on scrolling through HTML elements with the arrow keys, but nothing on integrating the enter key to select an item and redirect to a page.

I know there are auto suggest plugins available, but I've come this far in developing my own and I want to be able to customize the results instead of relying on someone else's work.

If anyone could steer me in the right direction, I would greatly appreciate it.

Cheers

Answer №1

This particular response would fall into the realm of 'guiding in the right direction' as I am unaware of your current code status.

You mentioned having already set up a dropdown with suggestions, so I will skip over CSS and JS for styling and placement.
Let's consider the dropdown being structured like this:

<div id="suggestiondropdown">
    <span class="suggestion" data-page="[URL of page]">Suggestion 1</span>
    <span class="suggestion" data-page="[URL of page]">Suggestion 2</span>
    <span class="suggestion" data-page="[URL of page]">Suggestion 3</span>
    <span class="suggestion" data-page="[URL of page]">Suggestion 4</span>
    <span class="suggestion" data-page="[URL of page]">Suggestion 5</span>
</div>

Using this JS code, you should be able to navigate through the suggestions using arrow keys:

var suggestions = document.querySelectorAll(".suggestion"); // 'suggestions' is now an array containing the spans
var index = 0;
document.onkeypress = function(e) {
    // Implement desired styling for the selected suggestion here:
    suggestions[index].style.backgroundColor = "#FFFFFF";
    if (e.keyCode == 38) { // UP arrow pressed!
        if (index <= 0) index = suggestions.length;
        index--;
    }
    else if (e.keyCode == 40) { // DOWN arrow pressed!
        if (index >= suggestions.length -1) index = -1;
        index++;
    }
    else if (e.keyCode == 13) { // ENTER key pressed!
         var page = suggestions[index].dataset.page;
         window.location.href = page; // If using relative URLs, be sure to add the base URL.
    }
    // Style the selected suggestion here.
    // For now, I'll just give the selected one a blue background.
    suggestions[index].style.backgroundColor = "#0000FF"; // Apologies for the unattractive shade

}

Not Tested

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

Tips for speeding up page loading when using the same image multiple times on a page

Is it possible to utilize a JavaScript Image object? If yes, could you provide an illustrative example? And is it feasible to achieve this with jQuery? ...

Having difficulty handling redirections in Node.js

I am encountering a new issue with the code provided. My goal is to create a simple login system, but I am facing difficulties in redirecting users using res.redirect('/example'). When attempting to redirect users, the console.log indicates that ...

Every time I restart the server with MEN stack, I encounter an error message stating "Cannot read property 'name' of null"

I am currently working on developing a campgrounds application based on Colt Steele's Udemy course "The Web Developer Bootcamp". Everything is going smoothly except for one issue I encountered. When I restart the server and directly access the URL wit ...

Unable to attach eventName and callback to addEventListener due to the error message stating 'No overload matches this call'

I am attempting to attach an event listener to the input element stored within a class method. This method takes a props object containing eventName and callback. public setTextFieldInputListener({ eventName, callback }: TextFieldListenerProps): void { ...

Endless cycle within the while loop without any obvious cause

I've been tinkering with a timer and thanks to some feedback I received in this community, everything is running smoothly. Here's what the current version looks like for reference: https://i.stack.imgur.com/Qd7ll.png Here's a snippet of my ...

Selecting a directive's scope

Though the title may not capture it quite accurately, I struggled to find a more fitting description. I crafted a directive that incorporates an ng-repeat: app.directive('appDirective', function($purr){ var template = '' + ...

Verify if the nested arrays within the object consist of any empty elements

Take a look at the object below: { "params": { "time_to_diagnosis": [ { "field": "date_of_diagnosis", "value": "" }, { "field": "date_of_symptom_onset", "value": "2019-09-01" } ], "time ...

"When a Vuex mutation modifies the state, the computed property fails to accurately represent the changes in the markup

I've encountered a perplexing issue with using a computed property for a textarea value that hasn't been addressed in a while. My setup involves a textarea where user input is updated in Vuex: <textarea ref="inputText" :value="getInputText" ...

Utilizing AJAX for file and data uploading in combination with Spring MVC and JSP

Struggling to create code for file and data uploading... Finding it difficult...!!!!!!!! Clicking "btn-upload" button does not trigger any response... No error message in eclipse... Seeking help, please assist...! This is JSP. <script> $("#btn- ...

Verify the validation of the text box

Checking a textbox control for validation is necessary. Validation Criteria: Value should be between 0 and 1000, with up to 2 decimal places (e.g. 1.00, 85.23, 1000.00). Once 2 decimal points are used, users should not be able to enter additional ze ...

Having trouble getting my app.get calls to work in the new Node Express project

Recently, I kicked off a new project and encountered a perplexing issue - my app.get method simply refuses to be invoked. The site keeps loading indefinitely without any content being displayed. Initially, I copied and pasted the code from another project ...

Is there a way to receive notifications on an Android device when the real-time data updates through Firebase Cloud Messaging (FC

I am attempting to implement push notifications in an Android device using Firebase Realtime Database. For example, if an installed app is killed or running in the background, and a user posts a message in a group (resulting in a new child being added in t ...

Conceal certain components when a user is authenticated

Below is the content of my app.component.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class='container'> <ul class="nav navbar-nav"> <li class='nav-item'> <a clas ...

Incorporating fresh visuals into the Fotorama presentation

Currently in search of a reliable jQuery image slider with thumbnail previews for a web application I am developing. Initially interested in Fotorama.js as it meets most of my criteria, but unsure if it supports adding additional images via AJAX after in ...

The correct way to extract a jwt token from headers and integrate it into an express application

After successfully implementing both the frontend and backend in express.js with authentication and authorization using JWT, I have confirmed that the JWT token is being properly set upon login. You can see the auth-token key in the image below: https://i ...

Invisible enigmatic anomaly detected on non-existent line within the realm of Node.js

Today, when I tried to run my app on node, it encountered an unexpected token error at line 219 in the file. The full error log is as follows: syberic@syberic:~/Web/lotalot$ node app.js /home/syberic/Web/lotalot/config/passport.js:219 }); ^ SyntaxError: ...

Has Next.js incorporated a maximum cache size feature along with an invalidation algorithm like LRU?

Currently, I have a Next.js site that utilizes getServerSideProps for data fetching. However, I am interested in switching to getStaticProps and implementing incremental static regeneration (ISR) for improved performance. Currently, my memory usage is ap ...

Struggling to repair the unresponsive on-click event even after thorough debugging efforts

i am working on a project where i have to create a datatable, but I am facing an issue with the edit event not firing on click. Even after debugging, it is not pointing towards any error. function GetLoginData() { $.ajax({ url: '/LoginMas ...

JavaScript - Unexpected fluctuations in variable values

After studying Japanese language, I decided to try my hand at experimenting with JavaScript by creating a simple FlashCard game for a project. The game generates an array of random numbers, fills the divs with 6 possible choices using jQuery, randomly sele ...

The MaterialTable is unable to display any data

After calling the fetch function in the useEffect, my getUsers function does not populate the data variable. I am unable to see rows of data in the MaterialTable as the data structure is in columns. I need help figuring out what I'm doing wrong. func ...