Steps for highlighting specific character(s) within a textarea

I am working on a program to search for specific characters within a designated <textarea> element. I want to be able to highlight or color the characters that match the search criteria within the text area. How can I achieve this effect and color the character(s) within the <textarea>? For example, if a user enters 'a' in the input field, then all instances of 'a' within the <textarea> should be colored red.

HTML

<form method="post" name="searching" onSubmit="return check(this)">
    <table border="0" cellpadding="10px" align="center">
        <tr><td width="114">
                <label><b>Text</b></label></td>
                <td width="287">
                <textarea name="para" cols="30" rows="10"></textarea>
            </td>
        </tr>
        <tr>
            <td>
                <label><b>Alphabet</b></label>
            </td>
            <td><input type="text" name="character" title="Enter Character">
        </tr>
        <tr>
            <td colspan="2" align="center">
                <input id="btn" type="submit" name="submit" value="Search">
            </td>
        </tr>
    </table>
</form>

JS

<script language="javascript">
    function check(form)
    {
        if(form.para.value==""){
            alert("No text is available for search!!");
            return false;
        }
        if(form.character.value=="")
        {
            alert("Search keyword is not Enter!!");
            return false;
        }
        para=new Array();
        index=new Array();
        keyword=form.character.value;
        para=form.para.value;
        found=0;
        k=0;
        for(i=0; i<para.length;i++)
        {
            if(keyword==para[i]){
                found+=1;
                $(document).ready(function(e) {
                    $("textarea:eq(i)").css("color","#FF0000");
                });
                index[k++]=i;
            }
        }
        if(found!=0){
            alert(found+" times "+keyword+" in text");
            alert("Index of alphabet: "+index);
            return false;
        }
        else{
            alert("Not found in the Text!!");
            return false;
        }
    }
</script>

I am open to any solutions, whether they involve CSS, HTML, JS, or jQuery. Thank you.

Answer №1

According to @Mohamed-Yousef, it seems that inserting tags or styles directly inside a <textarea> is not possible.

One workaround could be using a user-editable <div>, where additional tags with styles can be inserted through Javascript.

For instance:

<div contenteditable="true">
<!-- Works like a textarea, but with different default styles and functionalities -->

    This is the text where you want to apply styling.

</div>

By doing this, a JavaScript function can be created to wrap styled elements around specific characters, such as "e". This would result in the <div> (textarea) displaying content like this:

<div contenteditable="true">

    This is th<span style="background-color: yellow">e</span> text in which we want to emphasize.

</div>

You can test out a live example here (it actually worked quite well, surprisingly).

Answer №2

When attempting to modify text within a textarea, it is not possible because textarea elements only contain plain text. To apply formatting to specific words, you must surround these words with HTML elements. This approach is demonstrated in this JSFiddle. You can also search for multiple words by entering them with spaces in the search box, like item1 item item3:

var div = $('#text'), kw, keywords, i, j;
$('#btn').on('click', function (event) {
    event.preventDefault();
    console.clear();
    kw = $('#keywords').val();
    keywords = kw.split(" ");
    text = div.text();
    text = text.replace(/,|\.|\?/i, "");
    text = text.split(" ");
    for (i = 0; i < text.length; i++) {
        for (j = 0; j < keywords.length; j++) {
            if (text[i] == keywords[j]) {
                text[i] = '<span class="hl">' + text[i] + '</span>';
            }
        }
    }
    text = text.join(" ");
    div.html(text);
});
div {
    width:400px;
    height:250px;
    display:block;
    overflow:hidden;
    border:lightgrey 2px inset;
    padding:1px;
    overflow:hidden;
    overflow-y:scroll;
}
.hl{
    background-color:orange;
    padding:2px 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form name="form">
    <input id="keywords" type="text" value="">
    <input id="btn" type="submit" value="Search">
    <div id="text" contentEditable=true>Skinny grinder, redeye whipped, cream aftertaste, aroma white sit brewed fair trade froth. At, aroma, caffeine as, cream shop chicory, wings kopi-luwak espresso cream lungo. Siphon pumpkin spice ut plunger pot americano single shot robusta kopi-luwak. So, half and half mug instant frappuccino, trifecta caramelization mazagran sit black.

Sit americano cup, blue mountain coffee, blue mountain, breve cinnamon instant grounds cappuccino. Espresso plunger pot trifecta, redeye sit, qui ristretto bar caramelization turkish carajillo. Qui caramelization pumpkin spice crema skinny frappuccino sit turkish. Dark affogato, filter americano est mocha cream frappuccino.

Ut qui, arabica froth affogato shop, fair trade cultivar espresso kopi-luwak black. Cortado, instant crema flavour saucer mocha brewed. Single shot extra, est frappuccino half and half, fair trade qui acerbic lungo cappuccino grounds beans. Flavour irish kopi-luwak decaffeinated eu cream dripper cultivar cup cappuccino.

Dripper, americano that latte sit skinny in percolator coffee coffee half and half. Extraction wings cultivar roast, whipped french press arabica affogato dripper coffee. Crema to go, coffee cortado breve americano eu viennese. Redeye affogato, seasonal that medium roast viennese.

That at dripper, robusta frappuccino crema filter ut seasonal latte. Breve, qui con panna, saucer cinnamon flavour caramelization foam decaffeinated galão con panna. In medium coffee est trifecta shop at chicory acerbic rich aged. Cultivar mug white decaffeinated crema affogato, brewed caramelization beans blue mountain mocha.

Skinny, seasonal sweet, arabica caramelization wings carajillo rich. Flavour et shop aged at, caramelization trifecta instant a steamed. As, irish seasonal steamed instant espresso frappuccino. Affogato barista aroma dripper macchiato siphon skinny cup strong.

Kopi-luwak white spoon mazagran sugar so café au lait. Sugar blue mountain mug siphon wings cup roast affogato. White black café au lait frappuccino body, white flavour strong americano grounds sit kopi-luwak. Turkish, mocha, bar seasonal mug ut skinny.

Beans mug percolator espresso caffeine filter caramelization. Black barista percolator aftertaste, saucer frappuccino french press body white. Medium id wings grounds americano crema roast. Dripper, frappuccino mocha est robusta, sit est milk medium body caramelization doppio.</div>
</form>

Answer №3

Give this a try by changing the div to editable

function validateForm(form)
{
    var content=document.getElementById('content').innerHTML;
    console.log(content);
    if(content==""){
        alert("No text available for search!!");
        return false;}
    if(form.keyword.value=="")
    {
    alert("Search keyword is not entered!!");
    return false;
    }
    textArray=new Array();
    indexArray=new Array();
    searchKeyword=form.keyword.value;
    textArray=content;
    found=0;
    i=0;
    console.log(content);  
    content=content.replace(searchKeyword,'<span style="background-color: yellow">'+searchKeyword+'</span>');
    console.log(content);
    document.getElementById('content').innerHTML=content;
    if(found!=0){
        alert(found+" occurrences of "+searchKeyword+" in text");
        alert("Character index: "+indexArray);
        return false;
    }
    else{
    alert("Search keyword not found in the text!!");
    return false;}
    }

<div name="textArray" cols="30" rows="10" contentEditable=true id="content">hello World</div>

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

Having trouble with the fancybox form

Take a look at this link for information on how to display a login form. Once you click on "Try now", follow these steps: A fancy box should open with fields for name and password. If both fields are left blank and the login button is clicked, an error ...

One of the two identical pages is experiencing issues with the jQuery leanmodal while the other is

Despite having the same scripts and libraries loaded in two pages with identical templates, there is a slight difference in main content. Strangely, leanmodal only seems to work on the index page and not on any other page. <script type="text/javascrip ...

Implementing jQuery .load to effectively extract the Title tag from HTML code

I am currently utilizing .load to fetch and load pages, as well as modify their window titles. The page loads successfully; however, the main issue I am facing is my inability to extract the title from the HTML code present in the response. Below is the c ...

"Utilizing Bootstrap's form-check feature places the checkbox alongside the text

While attempting to create a checkbox using the Bootstrap form-check class, I encountered an issue with my code. Here is the snippet: <form> <div class="form-section"> <div>Title</div> <div class="form-check"> ...

Convert all page links to post requests instead

Currently, I am working on a JavaScript project where my objective is to transform all links on the page into forms. This will enable the requests to be sent using the POST method rather than the GET method. The code I have implemented so far is as follow ...

What is the best method to find a matching property in one array from another?

I am working with two arrays in TypeScript. The first one is a products array containing objects with product names and IDs, like this: const products = [ { product: 'prod_aaa', name: 'Starter' }, { product: 'prod_bbb&apos ...

I aim to break down a function into several functions using jQuery and AJAX for better organization and efficiency

I am working with a JavaScript file that includes an Ajax function to fetch data from a JSON file on a server. The goal is to interpret this data into a table, but I would like to break down the process into separate functions for generating links, dates, ...

Transitioning from left to right, picture smoothly scrolls into view using Way

I've explored various websites and even attempted to decipher a waypoint guide, but unfortunately, I haven't had any success. The scroll function doesn't seem to be working with the code below. (source: ) Any assistance on this matter would ...

What is the best way to ensure the network is idle after clicking on an element in puppeteer?

Is there a way to wait for network idle after clicking on an element in puppeteer? const browser = await puppeteer.launch({headless: false}); await page.goto(url, {waitUntil: 'networkidle'}); await page.click('.to_cart'); //Clicking o ...

The intersection observer fails to detect any new elements or entries that are appended to the page after it has

When I press the "add section" button to create a new section, the intersection observer does not seem to observe it. Even when I try to run the observer again after pressing the button, it still doesn't work. I suspect that I need to reassign the `se ...

ng-repeat is not functioning properly despite the presence of data

Currently, I am in the process of building a basic Website using the MEAN stack, but I'm facing an issue with an ng-repeat that is failing to display any content. Oddly enough, when I attempt something similar in another project, it works perfectly fi ...

Securing API data: Utilizing encryption techniques in express and nuxtjs to deter scraping efforts

I'm looking for a secure way to encrypt my API data in order to prevent users from viewing it in the network tab or as plain text within objects like window.__nuxt__. Currently, I am following these steps: Encrypting data on the back-end using a sec ...

Why does the event fail to trigger in an Angular 5 Kendo grid when the last character is deleted from the input box?

I have implemented a multi-filter in my Kendo Grid for an Angular 5 application. However, I am facing an issue where the event is not firing when the last character is deleted from the input box. How can I resolve this issue? For example, if I type ' ...

Synchronous execution in Node.js: Best practices for coordinating tasks

While Node.js is known for its asynchronous nature, I am seeking to perform tasks in a sequential manner as outlined below: 1. Make an API request > 2. Convert the body from XML to JSON.stringify format > 3. Pass the string to a template. request.g ...

Highcharts 3D Pie Chart with Drilldown Feature

How can I create a 3D Pie Chart with Drilldown effect? I am having trouble understanding how it works. Here is a JsFiddle Demo for a 3D Pie Chart: JsFiddle Demo And here is a JsFiddle Demo for a 2D Pie Chart with Drilldown feature: JsFiddle Demo You can ...

Effortlessly altering values within a dynamic key in Firebase's real-time database

I attempted to redefine the value as "pretend" using the code snippet below, but unfortunately it did not succeed. dataBase.ref().orderByChild('en_word').equalTo('pretend').set({ en_word: 'Pretend' }) ...

The images fail to load on Mozilla browser and appear as blank spaces

My images are only displaying as white in Mozilla but fine on other browsers. I've tried using -moz without success. It's a simple fix that I can't seem to locate. Any help would be appreciated. Just a quick note, the images appear blank wh ...

"Performing a row count retrieval after updating records in a Microsoft SQL Server database

Recently, I have been utilizing the MSSQL NodeJS package (https://npmjs.org/package/mssql#cfg-node-tds) in order to establish a connection with a MS SQL database and execute UPDATE queries. One thing that has caught my attention is that when an UPDATE que ...

Link the Sass variable to Vue props

When working on creating reusable components in Vue.js, I often utilize Sass variables for maintaining consistency in colors, sizes, and other styles. However, I recently encountered an issue with passing Sass variables using props in Vue.js. If I directly ...

Error encountered while running a mounted hook in Vue.js that was not properly handled

I have created a To Do List app where users can add tasks using a button. Each new task is added to the list with a checkbox and delete button next to it. I want to save all the values and checked information on the page (store it) whenever the page is ref ...