4

I'm curious if there's a way to style content in a textarea as a user types.

For example:

<textarea>abcdefghijklmnopqrstuvwxyz</textarea>

Could I highlight all the vowels in the above textarea string on screen using javascript? But still only send the string when the form is submitted?

Ryan
  • 14,682
  • 32
  • 106
  • 179

6 Answers6

4

You can use a div with contentEditable attribute instead of textarea and to do the highlighting there.

https://developer.mozilla.org/en-US/docs/HTML/Content_Editable

You will still need to copy the content of this div to a hidden field of a form if you need to post it.

Aidas Bendoraitis
  • 3,965
  • 1
  • 30
  • 45
1

give some id to textarea and bind its onkeyup event with jquery function.something like this

$('#id_of_textarea').bind('keyup', function() { 
//for displaying vowels on screen
var str=$('#id_of_textarea').val();
var total_findVowels="";
for (var i = 0; i < str.length; i++) {
if (str.charAt(i).match(/[a-zA-Z]/) != null) {
// findVowels
 if (str.charAt(i).match(/[aeiouAEIOU]/))
 {
  total_findVowels=total_findVowels+str.charAt(i);            
 }
}
 //use some label to display all vowels
  $("#some_lbl").text(total_findVowels);
 }//for
} );
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

try this

<div contenteditable="true">
          This text can be edited by the user.
 </div>
0

You can see one of those questions for some inspiration. They talk specifically about live syntax highlighting so is it not exactly what you are asking about but maybe close enough, and syntax highlighting seems to be a more common problem so it's easier to find some ready solutions:

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177
0

If beeing precise and answer only your question: There is no way to do it, but as others said there are other ways to solve your task

Roman
  • 504
  • 4
  • 10
0

I use the following snipplet:

$( "#yourtextarea" ).bind( "keyup input paste", parseAndReplaceContent );

My parseAndReplaceContent function calls jQuery's $( "#yourtextarea" ).val() to access and modify the data.