Sometime you may want to insert a `tab` character (for indent) in a `textarea` element. By default when user hit the `tab` key the current focus element will move to the next element.
### Add a \t into your current position
By insert a `\t` character right after the current cursor position
```js
// target element
$('#my-textarea').on('keydown', function(evt) {
// get the key code
var keyCode = evt.keyCode || evt.which;
// tab key
if (keyCode == 9) {
// prevent default action of key down
evt.preventDefault();
// get the textarea DOMElement
var textarea = this;
// get the value of textarea
var value = $(textarea).val();
// get the cursor current position
var start = textarea.selectionStart;
// get the cursor selection end position (if there some text selected)
var end = textarea.selectionEnd;
// string before start position
var start_string = value.substring(0, start);
// string after end position
var end_string = value.substring(end, value.length);
// insert string
var insert_string = '\t';
// insert the insert string between string string and end string
var new_value = start_string + insert_string + end_string;
// set a new value to textarea
$(textarea).val(new_value);
// set the cursor position right after the string just inserted
textarea.setSelectionRange(start + insert_string.length, start + insert_string.length);
}
});
```