Hi guys,

I know there are about a dozen posts similar to this one, but IŠve read them all, and none of them seem to give a straight answer.

So, what I want to do is add text to a textarea when a button is clicked. However, I don't just want it appended at the end, but inserted at the point where the cursor/caret currently is.

Having browsed the various posts above, IŠve put together the following:

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
  <head>
	<title>Title</title>
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
	<script type="text/javascript">
	  function insertText(elemID, txt)
	  {
		var elem = document.getElementById(elemID);
		
   if ( typeof elem.caretPos == 'undefined' ) // Opera 7 ??
	elem.value += txt;
   else 
	elem.caretPos.text = elem.caretPos.text.charAt(elem.caretPos.text.length - 1) == ' ' ? txt + ' ' : txt;
  // elem.innerHTML += text;
	  }
	</script>
  </head><body>
  
	<form>
	  <textarea id="txt1" cols=20 rows=20></textarea>
	  <input type="button" value="Insert some text" onclick="insertText('txt1', 'Hello');">
	</form>
  </body>
</html>
Judging by the code (and keeping in mind that my JavaScript knowledge is limited) this should work, but it doesn't. In stead of inserting the text at cursorpoint, it appends the text at the end. What am I doing wrong? Does the textarea loose information about its caret position when I click the button?

Thanks a whole bunch in advance !