View Full Version : Insert Text at Cursor

04-18-2005, 08:07 PM
I'm trying to put together a simple a editor that allows users to click a link and have it insert text into a text field. While I can find something that works like this on elsewhere, I have a bit of a special requirement. I need it to be able to put text where the cursor is. There are two text fields that the same set of links to insert text can operate on.


<form method="post" action="">
<textarea id="field1" name="field1"></textarea>
<textarea id="field2" name="field2"></textarea>
<a href="#" onclick="insert(<img src="picture1.gif" width="320" height="240" alt="picture1.gif")">Picture1.gif</a>
<a href="#" onclick="insert(<img src="picture2.gif" width="320" height="240" alt="picture2.gif")">Picture2.gif</a>


So depending on where the cursor last was, it would insert the text into that specific text field. Also, I need it to be able to specify the filename and other img tags where the function is called rather than in the javascript itself.

I'm trying to learn javascript, but I'm not finding much good info about it. Just seeing the code for this would really help me, but if you could comment some lines or at least point me in the right direction, I would be eternally grateful.

Thanks in advance

04-18-2005, 08:37 PM
IE only..or whatever...

04-18-2005, 08:55 PM
IE only..or whatever...

Thanks, but... From the looks of it, it doesn't cover the multiple textfields, and, more importantly, I need this to work in Mozilla/Safari browsers. If you find something that works in those browsers but not in IE, great!!! I don't need it to work in that browser.

04-19-2005, 05:02 AM
Try something like this:

<script type="text/javascript">
function insert(el,ins) {
if (el.setSelectionRange){
el.value = el.value.substring(0,el.selectionStart) + ins + el.value.substring(el.selectionStart,el.selectionEnd) + el.value.substring(el.selectionEnd,el.value.length);
else if (document.selection && document.selection.createRange) {
var range = document.selection.createRange();
range.text = ins + range.text;

<input type="button" value="hello" onclick="insert(this.form.ta,'hello')">
<input type="button" value="my freind" onclick="insert(this.form.ta,'my friend')">
<br />
<textarea rows="7" cols="30" name="ta">
This is sample text, click anywhere in here then
choose on of the buttons above to see text inserted.

01-04-2007, 04:40 AM

I got so excited when I found this! I installed and it wouldn't work... so I started debugging... and then I realised I need it to work where the button is not enclosed in the form tag. Is this possible?

My textarea is on one side of my page and my instructions and tips are on the other. Using a button to add a firstname is on the tips side of my page.

Other than that - it's perfect! Can someone please help?