Swap out the content in a text input box with the text chosen from a suggested autocomplete option

I am working on a text input box with auto-complete options displayed below it. I want to enable users to navigate through the options using keyboard arrows and "select" one, causing it to change color. How can I update the text in the input box with the selected option, similar to what search engines do?

<input class="searchBox" id="searchBox" name="q" type="text" autocomplete="off" placeholder="hi">

<div class="autoSuggestContainer">
  <span>Select from Menu</span>
    <a>history</a>
    <a>hilton</a>
    <a>hip2save</a>
    <a>hillary clinton</a>
    <a>hickok45</a>
    <a>hitler</a>
    <a>hibiscus</a>
    <a>hipaa</a>
</div>

For the full code including HTML, CSS, and Javascript implementation, you can access it via this link: https://jsfiddle.net/qckyu5e6/

Answer №1

Once you toggle the selected class for moving up and down, you can extract the anchor tag containing the text with the selected class and set it to the input tag. Check out this example

    $("#searchBox").val($(".selected").text());

Answer №2

By following this method, you can achieve the desired outcome:

$('.searchBox').val($(".selected").text());

To activate it, you must include a new case in your keyDown event to handle the 'enter' key, as well as a click event:

document.onkeydown = function (e) {
  e.preventDefault();
  
  switch (e.keyCode) {
    case 38:
      moveUp();
      break;      
    case 40:   
      moveDown();
      break;
    case 13:
      //handle enter key
      setInputText($(".selected").text());
      break;
    }
};

$(".urlnamelinkAS").on("click", function () {
    setInputText($(this).text());
});

function setInputText(text){
    $('.searchBox').val(text);
}

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

Ensuring jQuery filter() works seamlessly with Internet Explorer versions 6, 7, and 8

On my webpage, I have implemented an ajax call using the jQuery library to handle a specific task. After making the ajax call, I need to parse the response message that is returned. However, I encountered an issue with Internet Explorer versions 6, 7, and ...

Inspection Techniques for Javascript Objects

Is there a way to display an object's properties and methods in an alert box? When I try alerting an object, it only shows the nodename: alert(document); I'm looking for a way to see all the details of the object in the alert message. Is there ...

What is the reason why Prettier does not automatically format code in Visual Studio Code?

After installing and enabling ESLint and Prettier in my Nuxt application, I made the switch to Visual Studio Code. However, when I open a .vue file and use CMD+ Shift + P to select Format Document, my file remains unformatted. I even have the Prettier ex ...

Leveraging the jQuery live() function to optimize heavy usage of Ajax on a website

Trying to ensure that all scripts are properly executed as content is loaded and removed from the page using jQuery load has been a challenge. The most effective approach so far has been the live function, but I have encountered difficulties in getting it ...

Error: The variable $ is not recognized during the import process

One file, bundle.js, contains the following: window.$ = window.jQuery = require('jquery'); import './app.js'; While app.js contains this code: $('#button').on('click', function(e) { ... }); As a result, I enc ...

Enhance Your Button with CSS3 Animation

While experimenting with CSS3 animations, I encountered a challenge when trying to apply an animation to a button upon clicking. The desired effect was for the button to zoom in, spin, and then zoom out, giving the appearance of flying off the screen. Surp ...

Error: Uncaught [🍍]: The function "getActivePinia()" was invoked without an active Pinia instance present. Ensure that you have called "app.use(pinia)" before attempting to utilize a store

I encountered an issue while trying to access a store in Pinia for my Vue web application. Despite installing Pinia and setting app.use(createPinia()), I keep receiving the following error message: Uncaught Error: [ ...

Encountering a problem when verifying if the data is in JSON format using JavaScript

I'm using JavaScript to determine whether an input value is in JSON format, but I've encountered a problem with a specific value. Below is my code explanation. isJSON = async(str) => { try { return (JSON.parse(str) && !!str); ...

Extend the row of the table according to the drop-down menu choice

I am working on a feature where a dropdown menu controls the expansion of rows in a table. Depending on the option selected from the dropdown, different levels of items need to be displayed in the table. For example, selecting level 1 will expand the first ...

Having trouble with Laravel PUT method not functioning correctly when using ajax to post data serialized from a form

When editing a post, I changed the form method to PUT using @method('PUT') <form action="{{ route('user.update', ['id' => $user->id]) }}" method="post" enctype="multipart/form-data" id=&q ...

Encountering an issue with resolving a local variable during the execution of a test with Protractor

I'm currently learning about async calls in protractor as a newbie to the tool. I am struggling to figure out how to handle a boolean variable that I set to true if any test case fails and the execution goes to the catch block for a promise. Below is ...

Having trouble loading HTML content from another file

Here is the code snippet in question: <script> var load = function load_home(){ document.getElementById("content").innerHTML='<object type="type/html" data="/linker/templates/button.html" ></object>'; } </script> ...

Vue event manager, accessible for all components

I have created a new Vue instance and assigned it to the window object, thinking that it would be accessible throughout all components. I expected this setup to allow me access to events emitted anywhere within my application. However, it seems like this ...

Tabulator automatically inserted 'numrow' after retrieving the data

I have a table of undetermined information (consisting of various columns and rows). I am now at the point where I need to utilize the function table.updateData(), but this function specifically requires the column id to be present in the data structure. S ...

Attempting to input data into elements that have been generated automatically

Trying to set values to elements with automatically generated id's: This code is functional: <input type="tekst" id="<?php echo $item->getId();?>"> <script> document.getElementById("<?php echo $item->getId();?>").v ...

Is there a way to identify if a user clicks on the scrollbar within my div element?

Is there a way to detect when someone mouses down on the scrollbar of a div element with scrollbars? ...

The carousel comes to a halt once it reaches the final slide and does not continue cycling

Currently working on a website project for a client and utilizing Bootstrap to create a carousel feature. I am specifically using Bootstrap 3.0. After searching for a similar issue here, I found two cases that resemble mine but unfortunately have no soluti ...

Styling the topbar with CSS includes adding a vertical separator that neatly wraps the content within the

I recently created a website using HTML and CSS, featuring a topbar. However, I encountered an issue while trying to insert a vertical separator between some of the icons within the topbar. Initially, when I added the separator-div, only the first three ic ...

Generating an error when the input is focused

Whenever I try to navigate to Facebook and focus on one of the registration input fields, an error pops up. I attempted to fix this issue by implementing some code, but unfortunately, it did not work as expected. _emptyCheck: function() { ...

Problem with React Native Camera: Camera display is not functioning correctly - React-Native-Vision-Camera Error

Hey there! I could really use some help with a tricky situation I'm facing in my React Native app, specifically regarding camera integration. Here's the scoop: The Issue: I'm working on a video recording application using React Native that ...