0

I'm looking for a way to apply some formatting to a single-line text input field in JavaScript. It would work like this:

The user types in a formula, such as:

(7 + 3) ^ x

As the user types, my code would format it using colour to look like this:

enter image description here

I can do the necessary parsing but I don't know how to apply these styles to the user's text as they edit.

I've been struggling to find the right thing to Google for. My searches mostly lead me to full-blown text editors.

Is there such a component? If not, can I achieve this with a <input type="text"...> field?

Steve McLeod
  • 51,737
  • 47
  • 128
  • 184

4 Answers4

2

Out of curiosity I built this: http://jsfiddle.net/hunter/npbDL/

This catches key strokes and inserts a span-wrapped character into an element. If the character maps to an item in the character-to-class collection it also gives that span the class specified.

It also handles enter and backspace.

You can probably take it from there...

hunter
  • 62,308
  • 19
  • 113
  • 113
  • That's interesting... a bit more low-level to implement that I would have liked but a good starting point... – Steve McLeod May 24 '11 at 11:56
  • If it makes you feel better I can make it a jQuery plugin. ;) That's not a ton of jQuery and I'm sure it can be optimized – hunter May 24 '11 at 12:20
  • it is great, and I really like it. It's just that I'm trying to find something similar that already exists. Because to get everything an end-user expects - blinking cursor, ^A to select all, adding like a native control, regardless of OS and browser - will be a less-than-trivial task! But if it doesn't exist, then I'll just have to bite the bullet. – Steve McLeod May 24 '11 at 14:43
  • You could apply this concept and write the formatted html of what is in a textbox to a div easily enough. – hunter May 24 '11 at 15:18
0

I think the only way you can achieve the styling you want is by wrapping HTML tags around individual characters then styling the tags, and I don’t think you can do that inside an <input type="text">.

There is the widely-supported contenteditable attribute which makes most elements editable, but I’m not sure that it allows this either. If no-one else provides a better answer, you might want to view source on the last example here: http://www.hyperwrite.com/Articles/contenteditable.aspx

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
0

You can't format a text field with various colors. You might be able to use colors in WYSIWYG editors... or Flash.

santa
  • 12,234
  • 49
  • 155
  • 255
0

I don't think you can change of individual characters in any <input> nor <textarea>. Look into source code of Etherpad for example - it uses similar system (not exactly the same - it highlights other stuff) and it might help you.

mrkva
  • 336
  • 2
  • 13