View Full Version : paste string into textarea onclick

12-28-2003, 09:58 PM
Hi, I have a page with a textarea named "textbox". There are also several image links on the page. What I want to do is have it so that when a user clicks on an image a a string variable of text is pasted into the textarea without deleting the current text. Much the way that the instant smiley tags work on forums like this when posting. You just click the smiley image on the left and it places the appropriate characters into the textarea.

I have the following, which pastes the text I want into the textbox. However, it only seems to work in IE and it simply deletes all previous text instead of adding the new to the old. That's what I want to fix.

<a href="javascript:;" onClick="textbox.value='New Text';">
<img src="igs/br.gif" border="0" />

I'm not asking anyone to write this for me. I have a programming background but have never worked with javascript before. A small project I'm on requires this function though, so I'd appreciate any ideas and pointers to any tutorials which would deal with this exact type of function.

Thanks in advance,

12-28-2003, 10:55 PM
The easiest solution would be to give an ID [attribute] to the textarea, and call it like this:

<a href="#" onclick="document.getElementById('myTextarea').value += ' extra text'; return false;>

Replace myTextarea with the ID of the textarea.
Rather than using the assignment operator ("=") you use the "add-by-value" operator ("+="), which is essentially the same as = var + x. For instance:

var x = 'blue';
x = 'green'; // x now equals 'green'
x += ' and blue'; // x now equals 'green and blue'

Hope that helps!

Happy coding! :)

12-28-2003, 11:19 PM

That works good in IE, but still doesn't seem to work for NS. I'm okay with that if I have to limit users to those having IE installed. It is the primary browser out there anyway.

But, if I can find a way to give NS users functionality too that would be great. The project is a port of a software program from a Windows based software to a web-based version. The reason being that *nix and Mac users weren't able to use the PC based version, so using PHP and javascript I'm attempting to make the software OS cross-platform. So, the more browser compatability I can create the better.

Also, as it is the code pastes the "New Text" at the end of the textarea old text, is there a way to allow users to place their carrot anywhere within the texteare and have the "New Text" be pasted where the carrot is located? This would allow users to paste a new string of text within an existing paragraph for instance?

Any and all ideas are welcomed and appreciated.

Thanks again,