Modify the color of the text input by the user in an AJAX-enhanced text box

After successfully implementing an autocomplete textbox using AJAX Autocomplete, I decided to enhance the feature with some Fuzzy logic. Now, as the user enters 3 characters, my database returns a list of records that match those characters.

The search results are refined based on the input provided by the user, creating a progressively shorter and more accurate list.

Using the included CSS class of the Autocomplete control, I customized the background color and selected item color in the extended textbox.

            <asp:AutoCompleteExtender 
                ID="TextBox1_AutoCompleteExtender" 
                runat="server" 
                DelimiterCharacters="" 
                Enabled="True" 
                EnableCaching="True" 
                ServiceMethod="GetCompletionList" 
                ServicePath="~/search/strngSrch.asmx" 
                TargetControlID="TextBox1" 
                UseContextKey="True" 
                CompletionSetCount="30" 
                CompletionInterval="10"
                MinimumPrefixLength="2"
                CompletionListItemCssClass="itemHighlighted" 
                CompletionListHighlightedItemCssClass="itemHighlighted1">                    
            </asp:AutoCompleteExtender>

Now, I am looking to change the text color only in each string (list item) that matches what the user has entered after typing 3 or more characters.

Despite searching for a solution online for 2 days, I have been unable to find something similar, leading to frustration.

For example, if a user enters "fish," the results list should appear like this:

Fishing      (The 4 letters = to Fish should be red in each of these list items)

New Fishing licenses

Renew Fishing License

Fish and hatchery lists

If you have any links or solutions similar to what I described, I would greatly appreciate your help.

This functionality can be likened to searching for a specific text string in a PDF where the word is highlighted yellow in each occurrence within the document. I am open to changing either the background of the text entered by the user or changing the text color itself.

Thank you,

Answer №1

I want to express my gratitude to the helpful resource linked below for providing a solution to the problem. After much searching, I finally stumbled upon something that came close to resolving the issue at hand. In an effort to contribute more than just a hyperlink, please take a moment to review the functional code provided below.

Take note of some minor adjustments I made to the code below compared to the original version found in the aforementioned link.

    <script type="text/javascript"> 

function aceSelected(sender, e) {

    var value = e._item.innerText;       //  get_text();           

    if (!value) {
        if (e._item.parentElement && e._item.parentElement.tagName == "LI")
                    value = e._item.parentElement.attributes["_innerText"].value;
        else if (e._item.parentElement && e._item.parentElement.parentElement.tagName == "LI")
                    value = e._item.parentElement.parentElement.attributes["_innerText"].value;
        else if (e._item.parentNode && e._item.parentNode.tagName == "LI")
            value = e._item.parentNode._value;
        else if (e._item.parentNode && e._item.parentNode.parentNode.tagName == "LI")
                    value = e._item.parentNode.parentNode._innerText;
        else value = "";
    }

    var searchText = $get('<%=TextBox1.ClientID %>').value;

    searchText = searchText.replace('null', '');
    sender.get_element().value = value;
}

function acePopulated(sender, e) {

    //Give BehaviourId here
    var behavior = $find('AutoCompleteEx');
    var target = behavior.get_completionList();

    if (behavior._currentPrefix != null) {

        var prefix = behavior._currentPrefix.toLowerCase();
        var i;

        for (i = 0; i < target.childNodes.length; i++) {

            var sValue = target.childNodes[i].innerHTML.toLowerCase();

            if (sValue.indexOf(prefix) != -1) {
                var fstr = target.childNodes[i].innerHTML.substring(0, sValue.indexOf(prefix));
                var pstr = target.childNodes[i].innerHTML.substring(fstr.length, fstr.length + prefix.length);
                var estr = target.childNodes[i].innerHTML.substring(fstr.length + prefix.length, target.childNodes[i].innerHTML.length);                    
                target.childNodes[i].innerHTML = "<div class='autocomplete-item'>" + fstr + '<B><font color=red>' + pstr + '</font></B>' + estr + "</div>";
            }
        }
     }
  }         

When setting up your AutoComplete Extender, use the following parameters....

BehaviorID="AutoCompleteEx"  
OnClientPopulated="acePopulated"
OnClientItemSelected="aceSelected"

That covers most of it. Some tweaking and troubleshooting were necessary. Notable issues included the incorrect closing javascript tag and the function for retrieving the textbox value not working with e.get_value(), so I opted for e._item.innerText which appears to be functioning correctly.

Original Solution Source

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 content displayed within adjacent div elements

I am currently working on a project where I am dynamically generating an outline by creating panels and labels in ASP.NET. Each node in the outline is defined by an outline number and outline text, which are obtained from a database that defines the relati ...

Invoke a PHP function within a Bootstrap Modal using AJAX technology

My webpage features a list of users generated through a PHP loop. By clicking on each user's name, a Bootstrap Modal appears showcasing more information about the user. The hyperlink for each user looks like this: <a href="#user" data-toggle="mod ...

Is it possible to utilize router.push within Redux thunk? Is this considered a beneficial approach?

I have this anchor element: <a className="btn btn-sm btn-circle" href={`https://www.facebook.com/sharer/sharer.php?u=${ process.env.NEXT_PUBLIC_ENVIRONMENT == "prod" ? "https://tikex.com" : "https:/ ...

A Firefox Browser View of a Next.js and Tailwind Website magnified for closer inspection

After creating a website using Next.js and Tailwind CSS, I noticed that the site is appearing zoomed in when viewed in Firefox. However, it looks fine in all other browsers. When I adjust the screen to 80%, the website displays correctly in Firefox. What ...

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: // ...

Making an Ajax request to a RESTful web service from a different domain

Similar Question: Exploring methods to work around the same-origin policy I need to communicate with a RESTful web service from a different IP address using an AJAX request on my HTML page. Unfortunately, AJAX does not support cross-domain requests. ...

Grabbing nested JSON Array data using Node.js

As a beginner in Node.js, I’m attempting to extract data from the JSON below: var data1 = { "_id":"R1::table::A1::order::167::comanda::2", "_rev":"1-ed6df32d3b4df9cc8019e38d655a86f5", "comanda":[ [ { ...

Effective methods for importing components in VueJS 2.0

As a newcomer to VueJs, I have a question regarding the best practice for importing components in a Vue Template Project. I currently have some components that are used in multiple views. After downloading an admin template, I noticed that the samples alwa ...

Validation in Angular2 is activated once a user completes typing

My goal is to validate an email address with the server to check if it is already registered, but I only want this validation to occur on blur and not on every value change. I have the ability to add multiple controls to my form, and here is how I have st ...

The findByIdAndUpdate() function lacks the ability to modify the collection

I'm encountering an issue when trying to update a product using mongodb and redux. It seems that the database is not reflecting the changes after I attempt to update the product. Can someone please assist me with this problem? Here is my product.js f ...

Utilizing jQuery to determine the placement of a tooltip within a slider

I am currently utilizing both a jQuery Tooltip and a jQuery Slider (jQueryUI) simultaneously. While the slider is functioning correctly, I am encountering an issue where tooltips are being displayed in the wrong position after scrolling (view screenshot or ...

What is the process for dynamically checking in a node in jstree?

I am utilizing Jstree from https://github.com/vakata/jstree. I have successfully loaded the tree structure, and now I want to bind checked checkboxes from an array of data. By default, the nodes have unique ids. I will check the id of each node in the arra ...

What is the best way to position the label above the input text in a Material UI TextField component with a Start Adornment?

Struggling to figure out the right Material UI CSS class to style a reusable TextField component? You're not alone. Despite tinkering with InputLabelProps (specifically the shrink class), I can't seem to get it right. Here's the code snippet ...

Guide on how to retrieve and log a list of objects from a map using Puppeteer, based on elementsArray obtained through the use

I'm working on a Puppeteer script that is supposed to log a list of generated objects using the map method. const getFilteredOrders = async (page, pagesToFilter, error, paymentMethod, affiliationName) => { const { base, orders } = config.URL; ...

The Ajax request fails to set a value within the done callback

Here is a function I have: var isNameUnique = false; function ValidateName() { var url = "/SomeRules/CheckIfNameExists/"; var request = $.ajax({ url: url, method: "GET", data: { sName: name}, ...

Using jQuery to pass an array as part of an object literal for AJAX data transmission

I'm currently facing an issue with passing a dynamic object to jQuery ajax data in order to mimic the structure of serialized form data. This problem arises when I have a form with inputs using an array for the name, as shown below: <input type="t ...

buttons are arranged horizontally, stacked neatly on top of one another

I'm currently working on a setup for toggle buttons using absolute positioning for labels on top of checkboxes. My goal is to have them aligned horizontally, but instead, they are stacking on top of each other. <ul style="display: block; float: le ...

Instructions for creating a scrollable unordered list when it reaches its maximum capacity

My HTML code has a <ul> element with the following structure: <ul id="messages"> </ul> In my HTML file, I have not specified any <li> items. However, in my JavaScript code using jQuery, I dynamically add <li> items to the & ...

The CSS code seems to be ineffective when attempting to center elements with a specific width in react.js

Hey everyone, I'm currently working on developing a web application using react-bootstrap and I've encountered an issue with adjusting the width of my row and centering it. I have already created the necessary CSS and JS files, but I am unable to ...

Set up an event listener for when geolocation permission is approved

My Setup: I've written some basic code snippet below: const onSuccess = () => { console.log('success'); } const onError = () => { console.log('error'); } navigator.geolocation.getCurrentPosition(onSuccess, onError) ...