2

I have a line of text in the textarea is like below

<textarea>This is a line of text for test.</textarea>

Now I would like to change the word color of some character is like below. enter image description here

I don't want to change HTML textarea tag to display this text. I would like to implement is using jQuery. How can i do that?

Community
  • 1
  • 1
Optimus Prime
  • 308
  • 6
  • 22

3 Answers3

3

Here is a solution. but jQuery code runs only once

var alpha = ["s","x","e","T"];
var res = "", cls = "";
var t = $("#txt").text();

for (i=0; i<t.length; i++) {
    for (j=0; j<alpha.length; j++) {
        if (t[i] == alpha[j]) {cls = "red";}
    }
    res += "<span class='"+cls+"'>"+t[i]+"</span>";
    cls="";
}
$("#result").html(res);
.red {
    color: red;
}
#result {
    font-size: 24px;
    font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="txt">This is a line of text for test.</textarea>
<div id="result"></div>

It's possible to separate coloring of text if you use contenteditable element.

Here is fiddle of coloring particular chars on the fly:

http://www.codeply.com/go/YHx9yphpHW

Banzay
  • 9,310
  • 2
  • 27
  • 46
0

You can't change colors, but what you can do is select a particular character (highlight by way of JavaScript.)

See Highlighting a piece of string in a TextArea

Community
  • 1
  • 1
Muneeb Zulfiqar
  • 1,003
  • 2
  • 13
  • 31
0

Try this:

<textarea>This is a line of text for test.</textarea>

<script>
var counter = 0;
var newTextArea = new Array();
var currentText = $("textarea:first").val();

do{
    var currentLetter = currentText.charAt(counter);
    if(!(counter % 4)){
        $(currentLetter).css('color', 'red');
    }
    newTextArea.push(currentLetter);
    counter++;
}while(counter < currentText.length);

$("textarea:first").val(newTextArea.toString());
</script>
Adam Patterson
  • 958
  • 7
  • 13