Insert four spaces instead of a tab

I am trying to insert four spaces when the tab key is pressed. I used the following code (see spaces = "\t" ), but when I switch it to spaces = " " , only one place is inserted when I click the tab. I also tried "+" "+" "+" ":

 $(function () { $('textarea').keydown(function(e) { var keyCode = e.keyCode || e.which; if (keyCode == 9) { e.preventDefault(); var start = $(this).get(0).selectionStart; var end = $(this).get(0).selectionEnd; // set textarea value to: text before caret + tab + text after caret spaces = "\t" $(this).val($(this).val().substring(0, start) + spaces + $(this).val().substring(end)); // put caret at right position again $(this).get(0).selectionStart = $(this).get(0).selectionEnd = start + 1; } }); }); 

NOTE. This is needed to insert spaces in the browser-based / ide text area.

+5
source share
2 answers

Your code works fine, but you just put the carriage in the wrong place. Change the last line to:

 this.selectionStart = this.selectionEnd = start + spaces.length; 

DEMO: http://jsfiddle.net/qdqrs3cw/

+7
source

try inserting "    " instead of four spaces

PS Sorry, did not notice that spaces are needed in textarea, in this case HTML objects will not help

-1
source

Source: https://habr.com/ru/post/1210058/