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

Adding a Fictitious Pair to a JavaScript Object Literal

When I work with object literals in JavaScript, I often encounter syntax errors when adding a new label / value pair without including the trailing comma. This can be frustrating as it's easy to forget to include the necessary delimiter. .draggable({ ...

Building a multilingual website using AngularJS UI-Router

I am currently working on developing a multilingual website using AngularJS. While providing translations in templates seems straightforward, I am facing challenges when it comes to implementing proper multilingual routes using UI-Router. Unfortunately, I ...

What are the appropriate levels of access that an operating system should provide for web-based scripting?

Contemplating the level of access web-based applications have to an operating system has been on my mind. I'm pondering: What is the most effective method for determining this currently? Are we seeing a trend towards increased or decreased access? ...

I'm wondering how I can design a utility function within my Redux module that can extract a specific subset of read-only data from the current state

I am currently utilizing redux to create a "helper function" inside my redux module that is responsible for fetching filtered data from the state based on a specified index. This specific data will be used to generate a form consisting of inputs depending ...

What steps can be taken to turn off specific warning rules for CSS mode in ACE editor?

Utilizing the Ace Editor (through Brace and React-Ace) is a key aspect of my project. In our implementation, we specify the editor's mode as "css" and integrate it into our webpage. While this setup functions correctly, we have observed that some of ...

Tips for looping through client.get from the Twitter API with node.js and express

I am in the process of developing an application that can download a specific number of tweets. For this project, I am utilizing node.js and express() within my server.js file. To retrieve data from the Twitter API, I have set up a route app.get('/ap ...

The conversion of a 2D json array into a string is mistakenly performed

On hand is an outer array that contains 2 arrays within it, making it a 2-dimensional array. This is how the array is initialized: $outerArray = array(); $nestedArray = array("first", "second", "third", "fourth"); $outerArray[] = $nestedArray; $nest ...

Node-modules CSS

In my React application, I am utilizing CSS modules. By configuring modules:true in my webpack.config.js, I can successfully apply styles from files within my src folder. However, when importing components from node-modules, the corresponding CSS is not be ...

Updating an Object in vue.js Upon Click Event to Add a New Value

I currently have a code snippet that looks like the following: arr = [ { val1: a, val2: b }, { val1: a, val2: b }, { val1: a, val2: b } ] <div v-for="single in arr"> <button v-on:click="addSome"></button> </div> When I c ...

Creating a Validation Form using either PHP or JavaScript

I need to create a form with the following columns: fullname, email, mobile, and address. If the visitor fills out the mobile field, they should only be allowed to enter numbers. And if the visitor fills out the email field, they should only be allowed to ...

When a button is clicked within a partial view, it will redirect to the parent action

I am struggling with implementing an AJAX call using jQuery in a partial view within my application. I have a parent view called 'Parent' where I am using @Html.BeginForm and a submit button to save data. However, whenever I try to make the AJAX ...

Limit text to two lines inside a cell in a table

Apologies for not providing any evidence of my own efforts. I'm looking to wrap text in a table cell, but limit it to just 2 lines. Expanding the width is not possible. Any suggestions on how to achieve this? ...

Transform JSX into JSON or a string, then reverse the process

I am looking to store the state of a React Component in a database. Json.stringify(myComponent); However, when I attempt to reuse the component using JSON.parse, I encounter Error: Objects are not valid as a React child (found: object with keys {type, k ...

What is the rationale behind placing the CSS outside of the React function components, near the imports?

Recently, I encountered an issue with loading CSS inside a React function component using Material UI. Even though I managed to resolve it, I am still intrigued by the underlying reason. Initially, I had something like this setup where I placed both makeSt ...

Invoking a PHP function within a JavaScript file

I'm facing an issue with calling a PHP function from JavaScript. I have written a code snippet where the PHP function should print the arguments it receives, but for some reason, I am not getting any output when running this code on Google Chrome. Can ...

Tips for enhancing contrast in MUI dark theme modals

Currently, I am implementing MUI dark mode for my Next.js application. While the MUI modal functions perfectly in light mode, I am struggling with visibility issues when using it in dark mode. The contrast is not strong enough, making it difficult to disti ...

The absence of the 'Access-Control-Allow-Origin' header is reported even though it is actually present

I have been attempting to send a POST request from one website to my own site. Despite allowing CORS access explicitly, every time I try to make the actual POST request, I am faced with the No 'Access-Control-Allow-Origin' header is present on th ...

Display the Ajax response in a designated div

I am facing an issue with my ajax code. It doesn't print any output, but when I use alert() to print the output, it shows up fine. $(".grp-ans").each(function(e){ $.ajax({ type: 'POST', url: 'show-answ ...

strategies for chaining together multiple observables with varying data types and operations

Hey everyone! I'm facing a situation where I have a form with multiple select types, and the options for these inputs are coming from an API. I then take the data emitted from the HTTP request observable and feed it into my FormGroup, and everything i ...

Executing JavaScript code from an external link

Currently, I am in the process of developing a horizontal parallax website. The functionality is working seamlessly; when I click on the menu, the slides smoothly transition horizontally and display the corresponding content. However, I have encountered a ...