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

insertAtCaret: function(textToInsert){
  return this.each(function(i) {
    if (document.selection) {
      sel = document.selection.createRange();
      sel.text = textToInsert;
    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.selectionStart = startPos + textToInsert.length;
      this.selectionEnd = startPos + textToInsert.length;
      this.scrollTop = scrollTop;
    else {
      this.value += textToInsert;

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) {
        return false;

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


Leave a Reply

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