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?
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.