How to color specific character(s) in textarea

2020-04-17 05:11发布

问题:

I am making a program to search for characters in the desired <textarea>. I need to color the specific character that i found in text area. How can I color the character(s) in the <textarea>? For example, if i enter 'a' in input field than all the 'a's in the <textarea> should 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'm looking for any solution, be it in CSS, HTML, JS (or jQuery). Thanks.

回答1:

As @Mohamed-Yousef said in his comment, I don't think you can put tags or styles inside a <textarea>.

An alternative would be to use an user-editable <div>. With this, you can put additional tags with styles by JS.

For example:

<div contenteditable="true">
<!-- Editable like a textarea, but without some of its default styles and functions -->

    This is the text in which to highlight letters.

</div>

With this, if you search for "e", you can make a JS script to add styled elements around all the "e"s, so that your <div> (textarea) would look like this:

<div contenteditable="true">

    This is the t<span style="background-color: yellow">e</span>xt in which to highlight l<span style="background-color: yellow">e</span>tt<span style="background-color: yellow">e</span>rs.

</div>

Try this example (which actually turned out really well, I'm surprised).



回答2:

You can't change it in a textarea because textarea only contains pure text, to add format to words yo ufound you need to surround these matched words within html elements, so this why it won't work, as in this JSFiddle, just another way of doing it, you can search for multiple words if you separate them by a space 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>



回答3:

Try This as mentioned change div to editable

function check(form)
{
    var searchMe=document.getElementById('searchMe').innerHTML;
    console.log(searchMe);
    if(searchMe==""){
        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=searchMe;
    found=0;
    k=0;
    console.log(searchMe);  
    searchMe=searchMe.replace(keyword,'<span style="background-color: yellow">'+keyword+'</span>');
    console.log(searchMe);
    document.getElementById('searchMe').innerHTML=searchMe;
    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;}
    }

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