Entering tabs in HTML textarea components

authored by Frank Lynam at 04/02/2015 09:56:21

Have you ever wanted to let users enter tabs in a textarea on a webpage? If so, then read on because that’s exactly what I’m going to talk about in this post. Obviously the problem here is that while tabs are a very common requirement for a lot of webpage use scenarios, the default behaviour of a browser is to move the focus from the textarea on to the next component on the page, which is not what you want. I’ve written a small piece of JavaScript code that allows you to change this behaviour.

The HTML and JavaScript shown below is all that you need to try it out. I’ve used jQuery to help with the selection of elements and the getting and setting of the textarea’s value. Enjoy!

<!DOCTYPE html>
    <meta charset="utf-8" />
    <title>textarea tab experiments</title>
	<script src="http://code.jquery.com/jquery.js"></script>
	<script type="text/javascript" charset="utf-8">
		$(document).ready(function() {
			$('body').keydown(function(e) {
				if ($('#form-test textarea').is(':focus')) {
				    if ((!e.shiftKey) && (e.keyCode === 9)) {
						var nCaret = getCaretPosition($("#form-test textarea")[0]);
						if (nCaret >= 0) {
							var szText = $("#form-test textarea").val();
							var szNewText = (szText.substring(0, nCaret) + '\t' + szText.substring(nCaret));
							$("#form-test textarea").val(szNewText);
							setCaretPosition($("#form-test textarea")[0], nCaret+1);
					    if (e.preventDefault != null) {
						return false;

		function getCaretPosition(oField) {
			if (oField == null) {
				return -1;
			var nCaretPos = 0;

			// IE Support
			if (document.selection) {
				// Set focus on the element
				oField.focus ();
				// To get cursor position, get empty selection range
				var oSel = document.selection.createRange ();
				// Move selection start to 0 position
				oSel.moveStart ('character', -oField.value.length);
				// The caret position is selection length
				nCaretPos = oSel.text.length;
			// Firefox support
			else if (oField.selectionStart || oField.selectionStart == '0') {
				nCaretPos = oField.selectionStart;

			return nCaretPos;

		function setCaretPosition(oField, nCaretPos) {
			if (oField == null) {
				return oField;

			if(oField.createTextRange) {
			    var range = oField.createTextRange();
			    range.move('character', nCaretPos);
			else {
			    if(oField.selectionStart) {
			        oField.setSelectionRange(nCaretPos, nCaretPos);
			    else {
			return oField;
	<form id="form-test">
 				<label for="query">Query</label>
				<textarea id="query" name="query">Start tabbing here</textarea>