Style the input element for typeahead functionality

I am working on a simple textbox input that has the following appearance:

<input type="text" placeholder="Search for states">

My goal is to implement an autocomplete feature similar to typeahead. While I have successfully implemented the autocomplete functionality, I now wish to display the first suggestion directly in the textbox. Here's an example scenario:

After typing "Al," the suggestions provided are:

Textbox: Al

  • Alabama
  • Algeria

What I aim to achieve is having the text "Alabama" appear in the textbox with the word "abama" in faded text.

I am seeking guidance on how this can be achieved using jQuery or pure JS. Is it possible to apply different text styles to different substrings within the same input element?

If there are alternative methods (such as overlaying another transparent text control), I would appreciate seeing an example. It's important to note that modifying the input element itself is not an option.

Answer №1

Check out this code on CodePen: http://codepen.io/mozzi/pen/XKKJWq

This code snippet is similar to what you're looking for. I've opted for selecting text instead of fading it, since achieving half-faded text in a text box can be tricky. Let me know your thoughts on this approach.

Here's the HTML:

<div class="ui-widget">
  <label for="automplete-1">Enter a U.S. state name: </label>
  <input id="automplete-1" placeholder="U.S. state name">
</div>

And here's the relevant JavaScript:

$("#automplete-1").autocomplete({
  delay: 0,
  source: UsStateNames,
  response: function(event, ui) {
    var start = $("#automplete-1").val().length;
    $("#automplete-1").val(ui.content[0].value);
    var end = ui.content[0].value.length;
    $("#automplete-1")[0].setSelectionRange(start, end);
  }
});

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

Adding a JavaScript library to your Grunt project involves a few simple steps

I've been working on an existing project built with Ionic framework. I'm trying to integrate push notifications using Ionic's feature, but when running the grunt command, I encountered the following error: Running "jsbeautifier:files" (jsbe ...

Puppet Master: Retrieve the inner content

Is there a way to retrieve the innerHTML or text of an element? Or even better, how can I click on an element with a specific innerHTML? The approach in regular JavaScript would be as follows: let found = false; $(selector).each(function() { if (found ...

What is the best way to conceal an element by clicking anywhere other than on the element itself?

Currently, I am utilizing jQuery's toggle method to display or hide a page element when another specific page element is clicked. jQuery('a#mobile-search-icon).click(function(){ jQuery('#searchBox').toggle('slow'); }); ...

Tips for preserving input field data in an AngularJS scope variable

I am having trouble storing textbox values in my 'Values' variable. When I enter values in the textboxes, it seems to be getting the hard-coded values instead. Can someone please help me with this AngularJS issue as I am new to it? Here is the co ...

Guidelines for choosing an alternative language on a webpage using Selenium

Welcome to a website that provides tax information, accessible to everyone. Upon entering the site, I navigate to the 'Abzüge' section, only to find myself on an English page. Despite my attempts to switch to German, I struggle to locate the but ...

Axios successfully fulfills a promise despite the request being canceled while using React.StrictMode

In my React project, I'm using axios with React.StrictMode enabled by default, causing components to render twice. To handle this behavior, I've set up an abort control for my axios instance and call its abort() method in the useEffect clean-up f ...

Using d3.js to dynamically change the color of svg elements based on their data values

I was searching for a way to dynamically color SVG rectangles based on values from a dataset. If I were to create rectangles for each data entry, how could I adjust the rectangle's color according to the data value? Here is what I currently have: // ...

What could be the reason for the lack of definition of the `pieceOfText

My latest project involves a fun guessing game centered around decrypting text, but I've hit a snag with a variable in my JavaScript code. This variable, known as pieceOfText, should be assigned a random piece of text from an array containing 3 encode ...

Is there a way to make a link clickable but also prevent another link from being activated when clicked?

Have you ever utilized #link to navigate to a specific section on a webpage? You can also incorporate animate and scrollTop() to ensure a smooth scroll. However, when the #link (Hash link) is situated in the navigation menu, it must be structured as exampl ...

Pick a unique identifier for the <a> element and add an event listener to it

I am using an Ajax function to generate a table. Within one of the columns, there is an anchor field with a specific id. I am looking to trigger an event when that anchor field is clicked. Here is my current approach: $( "#26" ).on('click', &ap ...

What is the best way to invoke a function that is declared within a React component in a TypeScript class?

export class abc extends React.Component<IProps, IState> { function(name: string) { console.log("I hope to invoke this function"+ name); } render() { return ( <div>Hello</div> ); } } Next, can I cal ...

Verifying the presence of an image via its URL may not be functional across all browsers

Hey folks, I'm working on a project that involves displaying an image along with other fields in a loop where the image source changes with each iteration. I also need to check if the image exists and set a default source if it doesn't. The code ...

Locate and swap out a specific string within a variable using jQuery

After much searching, I have yet to find a solution to what I thought would be a simple question. Using the .clone() method, I successfully copied a li element containing multiple form fields and inserted it at the beginning of the form. My challenge now ...

Invoking a jQuery request to a C# API endpoint

I have recently embarked on a project utilizing ASP.NET MVC and JavaScript/jQuery. I am facing an issue where my API call to the controller using $.ajax function always returns a 404 error. Despite researching and trying various solutions, I continue to en ...

How to eliminate arrow icons from Bootstrap Carousel

Welcome to my blog at www.lowcoupling.com. I am trying to hide the left and right arrows on the bootstrap carousel, but my code doesn't seem to be working. Here is what I have tried: .glyphicon-chevron-right{ display:none; } (I also tried the ...

Encountering the error message "Cannot GET /" in a NodeJS Express

I've been experimenting with various approaches to resolve this issue, ranging from app.use(express.static(__dirname + "public")) to res.render. It seems to function correctly in my terminal environment but fails when I try to access it locally. Can a ...

Is there a way to extract a variable value from an external webpage in order to manipulate

Although I am not well-versed in PHP, I believe it may be the most suitable solution for achieving my goal. I want to extract the value of a variable from an external page in order to process it for generating graphs and statistics on my own webpage. The s ...

What is the best way to conceal content when the user clicks on the "more" button?

My HTML Code includes the following structure: ... @foreach($hotel as $key=>$value) ... <div class="iteration"> <input type='hidden' value='<?php echo $value['HCode& ...

What is the best way to notify my form that a payment has been successfully processed?

I'm working on a form that has multiple fields, including a PayPal digital goods button. Clicking on this button takes the user out of the website's workflow and into a pop-up window for payment processing. Once the payment is completed, the retu ...

The issue of loading SVG with textureloader in three.js has been reported not to work properly since version

I've had success using svg files with Three.js versions R76 and R77, but now in R78 I can only get it to work with pngs and jpgs var floor = new THREE.TextureLoader(); floor.load('layout.svg', function ( texture ) { var geom ...