Page 1 of 1

javascript add text into a form

Posted: Tue Dec 10, 2002 6:03 pm
by Sevengraff
Like the emoticons on this form, how can i use javascript to add something like Clicky smiles?

Posted: Wed Dec 11, 2002 1:48 am
by volka
well, phpBB does it this way

Code: Select all

...
function emoticon(text) {
	text = ' ' + text + ' ';
	if (document.post.message.createTextRange && document.post.message.caretPos) {
		var caretPos = document.post.message.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
		document.post.message.focus();
	} else {
	document.post.message.value  += text;
	document.post.message.focus();
	}
}
...

<textarea name="message" rows="15" cols="35" wrap="virtual" tyle="width:450px" tabindex="3" class="post" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup="storeCaret(this);"></textarea>
if you open the "more emoticons"-window the code is

Code: Select all

function emoticon(text) &#123;
	text = ' ' + text + ' ';
	if (opener.document.forms&#1111;'post'].message.createTextRange && opener.document.forms&#1111;'post'].message.caretPos) &#123;
		var caretPos = opener.document.forms&#1111;'post'].message.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
		opener.document.forms&#1111;'post'].message.focus();
	&#125; else &#123;
	opener.document.forms&#1111;'post'].message.value  += text;
	opener.document.forms&#1111;'post'].message.focus();
	&#125;
the only difference is the usage of the opener-element which refers to the opening window/frame

Posted: Thu Dec 12, 2002 6:52 pm
by Sevengraff
Ok, Looked at the code for the way phpBB does it, and some other scripts, and this seems to work:

Code: Select all

<script language="Javascript" type="text/javascript">
<!--
function insert(text) &#123; 
   text = ' ' + text + ' '; 
   if (document.post.message.createTextRange && document.post.message.caretPos) &#123; 
      var caretPos = document.post.message.caretPos; 
      caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text; 
      document.post.message.focus(); 
   &#125; else &#123; 
   document.post.message.value  += text; 
   document.post.message.focus(); 
   &#125; 
&#125;
//-->
</script>
 
 
<a href="javascript:insert(':)')">SMILE</a><p>
<form name="post" action="next.html" method="POST">
<textarea name="message" rows="15" cols="35" wrap="virtual" style="width:450px" tabindex="3" class="post"></textarea> 
</form>
Took me a while to see that you have to have <form name="post"> and <textarea name="message">. I dont know any javascript.