Reputation: 308
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.
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?
Upvotes: 2
Views: 5398
Reputation: 9470
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
Upvotes: 3
Reputation: 958
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>
Upvotes: 0
Reputation: 1023
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
Upvotes: 0