Ryan
Ryan

Reputation: 15270

Is there a way to style textarea content as the user types with javascript and css?

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?

Upvotes: 4

Views: 485

Answers (6)

Milind Anantwar
Milind Anantwar

Reputation: 82241

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
} );

Upvotes: 1

Benjamin Brizzi
Benjamin Brizzi

Reputation: 122

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.

Upvotes: 0

user1120073
user1120073

Reputation:

try this

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

Upvotes: 1

Roman
Roman

Reputation: 504

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

Upvotes: 0

rsp
rsp

Reputation: 111374

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:

Upvotes: 0

Aidas Bendoraitis
Aidas Bendoraitis

Reputation: 4003

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.

Upvotes: 4

Related Questions