Insert Text Into Textareas Using Javascript

The other day, I was working on a script to allow administrators to edit templates within the admin center of the content management system I’m developing. Rather than just using a plain textarea with the contents of the template files, I wanted to add some simple functions with javascript. First, I wanted to set it up so that the tab button would insert a tab rather than skipping to the next form field. Second, I wanted to add a list of the various template tags that can be used in the CMS, and allow the admins to click on one of those to insert it in the textarea.

I started Googling for information about inserting text at the current location of the cursor within the textarea. The first page I came across gave me a really good example to work from. I started building the javascript function and, within an hour or so, I had it working almost perfectly in Firefox (after Googling again to figure out how to stop the tab button from moving to the next form field – hint: preventDefault).

Once it was working, I opened up Internet Explorer and immediately got a javascript error. I then spent about two hours Googling for information and applying various fixes. Although I came across seven or eight different sites that claimed to have code that works in Firefox and IE, none of them really did. In all instances, when I applied the code provided on the pages, the text would be inserted in the wrong place within the textarea. With some scripts, a 0 would appear where the cursor was and at the beginning of the textarea, and the inserted text would appear somewhere in between the two. In other cases, the inserted text would just show up in the wrong place.

Near the end of my rope, I went to Google one more time, and finally came across a post on parentNode.org. The code provided there worked perfectly for my purposes. Every time I tested it in Firefox, Safari, IE6 and IE7, the script worked perfectly.

So, if you are looking for a cross-browser script to insert text into a textarea with javascript, check out the post on parentNode and ignore all of the other Google results. Good luck and happy coding.

Just in case the post or the code disappears, here it is. I take no credit for this code, whatsoever. I have simply copied it from the post on parentNode.

	function insertAtCaret(obj, text) {
		if(document.selection) {
			obj.focus();
			var orig = obj.value.replace(/\r\n/g, "\n");
			var range = document.selection.createRange();

			if(range.parentElement() != obj) {
				return false;
			}

			range.text = text;

			var actual = tmp = obj.value.replace(/\r\n/g, "\n");

			for(var diff = 0; diff < orig.length; diff++) {
				if(orig.charAt(diff) != actual.charAt(diff)) break;
			}

			for(var index = 0, start = 0;
				tmp.match(text)
					&& (tmp = tmp.replace(text, ""))
					&& index <= diff;
				index = start + text.length
			) {
				start = actual.indexOf(text, index);
			}
		} else if(obj.selectionStart) {
			var start = obj.selectionStart;
			var end   = obj.selectionEnd;

			obj.value = obj.value.substr(0, start)
				+ text
				+ obj.value.substr(end, obj.value.length);
		}

		if(start != null) {
			setCaretTo(obj, start + text.length);
		} else {
			obj.value += text;
		}
	}

	function setCaretTo(obj, pos) {
		if(obj.createTextRange) {
			var range = obj.createTextRange();
			range.move('character', pos);
			range.select();
		} else if(obj.selectionStart) {
			obj.focus();
			obj.setSelectionRange(pos, pos);
		}
	}

2 Responses

  • Rajan Ashrafi

    i want more info on javascript.
    currently i am doing jsp.
    if you have contents on javascript please send to my email.
    [email protected]

  • Jack

    I have looked for some javascript to implement MyWords functionality on my web resource and found http://vitana-group.com/article/javascript-dhtml/MyWords only. May be somebody knows something yet to I can compare and choose better for me. Vitana MyWords looks good and they are ready to modify it based on my requirements for payment.