There are solutions out there on the subject. We borrowed the following jQuery code from another post:

jQuery.fn.extend({
insertAtCaret: function(textToInsert){
  return this.each(function(i) {
    if (document.selection) {
      this.focus();
      sel = document.selection.createRange();
      sel.text = textToInsert;
      this.focus();
    }
    else if (this.selectionStart || this.selectionStart == '0') {
      var startPos = this.selectionStart;
      var endPos = this.selectionEnd;
      var scrollTop = this.scrollTop;
      this.value = this.value.substring(0, startPos)+textToInsert+this.value.substring(endPos,this.value.length);
      this.focus();
      this.selectionStart = startPos + textToInsert.length;
      this.selectionEnd = startPos + textToInsert.length;
      this.scrollTop = scrollTop;
    }
    else {
      this.value += textToInsert;
      this.focus();
    }
  })
}
});

However, if we think about usability, this might present as a nuisance to many experienced web users who prefer to tab through forms, especially if your textarea is an optional field.

To improve usability a bit, we can make an assumption that in most cases, users wouldn't normally place a tab after an alphanumeric character (as they would after a line-feed).

The code below allows us to keep track of the last key pressed, and if it is not alphanumeric, allow the tab to be inserted, otherwise, move to the next field. You may wish to adjust the criteria for allowing a tab by changing the ASCII code value(s).

lastKeyPress = 0;

$('textarea').keydown(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    // ASCII codes below 33 are reserved for special
    // characters such as space, line feed, carriage return, etc.
    if(code == 9 && lastKeyPress < 33) {
        $(this).insertAtCaret(String.fromCharCode(9));
        return false;
    }
});

$('#textarea').keypress(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    lastKeyPress = code;
});

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *