Is it possible to add a subscript tag to numbers as a user types into an textbox, for example if a user was to type in H20 it would instantly of converted to H20. I am looking for a solution using jQuery?
2 Answers
No, textboxes may not contain html-markup. But you can replace the 2 with a subscript-2-character ₂
(Unicode 2082 ).
Here the function :
function fx(e)
{
var k=String.fromCharCode(e.which);
if(k.match(/\d/))
{
var r=String.fromCharCode(8320+Number(k));
try{//IE
document.selection.createRange().text=r;
}
catch(x)
{//others
var o = e.target
var intStart = o.selectionStart;
var intEnd = o.selectionEnd;
o.value = (o.value).substring(0, intStart) + r +
(o.value).substring(intEnd, o.value.length);
o.selectionStart=o.selectionEnd=intStart+r.length;
o.focus();
}
return false;
}
return true;
}
Call this function onkeypress.
It replaces(if a number was typed) the current selection with the subscript of that number.
Unicode-char at position 8320(HEX 2080) is subscript-zero, it just adds the typed number to that position and retrieves the char at the new position.

- 116,463
- 16
- 195
- 201
-
So could you change all numbers as a user types them into an input box? – user786731 Jul 28 '11 at 20:37
-
Hey this worked perfectly thanks, is there anyway to increase the size of the numbers but not the letters after they have been changed to subscript? – user786731 Aug 02 '11 at 09:25
Update 2: The below suggestion doesn't seem to work in Chrome or Safari :( I originally tested it on Firefox. Anyway, it might be a useful starting point.
Update: As Dr.Molle pointed out, you cannot decorate the content of a regular <textarea>
with HTML markup. That said, you might look into using some sort of WYSIWIG library to achieve what you're after. For example, I was able to get a rough draft of the behavior you seem to want using TinyMCE. Take a look at this jsFiddle demo to see how it works.
Original answer: Here's a sort of hacky approach that you might be able to run with:
$("#text-input").keypress(function() {
var text = $(this).val();
$("#output").html( text.replace(/(\d+)/g, "<sub>$1</sub>") );
});
-
Am looking for the text in the input box to change as the user presses. Also instead of keypress which sort of runs once press behind kepup could be used. So if this could transform the value of the input text box on each press that would be perfect. – user786731 Jul 28 '11 at 20:32