开发者

Add subscript to numbers on the fly as user types using jQuery

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.

Demo: http://jsfiddle.net/doktormolle/KDgH9/


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜