3

I have following textarea field to write HTML code like Try It Editor.

<textarea class="form-control" required rows="15" id="code" 
Placeholder="আপনার HTML এবং CSS কোডগুলো এখানে লিখুন তারপর আউটপুট দেখার জন্য 
নিচের নীল বাটনটিতে ক্লিক করুন..." name="code"></textarea>

In this box, I need to use indentation. So if the box has no text then the indentation is working fine but if there is a text already OR you already typed something but now you want to add indentation then indentation is not working I mean It's going to the last line.

Here is the live link:

http://amarcourse.com/try-it-editor/input.html

Here is the JS code I use for that Indentation:

<script type="text/javascript">
    var myInput = document.getElementById("code");
    if(myInput.addEventListener ) {
        myInput.addEventListener('keydown',this.keyHandler,false);
    } else if(myInput.attachEvent ) {
        myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */
    }

    function keyHandler(e) {
        var TABKEY = 9;
        if(e.keyCode == TABKEY) {
            this.value += "    ";
            if(e.preventDefault) {
                e.preventDefault();
            }
            return false;
        }
    }
</script>
Shibbir
  • 1,963
  • 2
  • 25
  • 48

1 Answers1

2

var myInput = document.getElementById("code");
if (myInput.addEventListener) {
  myInput.addEventListener('keydown', this.keyHandler, false);
} else if (myInput.attachEvent) {
  myInput.attachEvent('onkeydown', this.keyHandler);
}
function keyHandler(e) {
  var TABKEY = 9;
  var TABVAL = "    ";
  if (e.keyCode == TABKEY) {
    if (document.selection) {
      myInput.focus();
      sel = document.selection.createRange();
      sel.text = TABVAL;
    } else if (myInput.selectionStart || myInput.selectionStart == '0') {
      var startPos = myInput.selectionStart;
      var endPos = myInput.selectionEnd;
      myInput.value = myInput.value.substring(0, startPos) + TABVAL + myInput.value.substring(endPos, myInput.value.length);
      myInput.selectionStart = startPos + TABVAL.length;
      myInput.selectionEnd = startPos + TABVAL.length;
    } else {
      myInput.value += TABVAL;
    }
    if (e.preventDefault) {
      e.preventDefault();
    }
    return false;
  }
}
<textarea id="code" placeholder="type something with tabs!"></textarea>

You need to insert the string at the current position. Answer based off of this one.

Aurel Bílý
  • 7,068
  • 1
  • 21
  • 34
  • Wow, Great, Working Fine. Can you suggest me a PHP Try It editor for a website like w3schools does? – Shibbir May 05 '19 at 11:14