View Full Version : Buttons with on click function

08-07-2008, 02:58 AM
I have some buttons that add text to a text area when they are clicked. I need to know how to get the cursor to be changed one that happens. Below is an example.

If the user clicks a button the text box would add



I want the cursor to then be on the line in-between those lines. But i can not make the cursor position static because there could be typing bolth before and after the text that the button inserts.

If anyone has and knowledge about this or can point me to a tutorial i would really appreciate it, thanks in advance for the help.

08-07-2008, 04:10 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function add(el, ta, t1, t2){
var t = el.form.elements[ta], l;
t.value += '\n' + t1 + '\n';
l = t.setSelectionRange? t.value.length : t.value.replace(/\n/g, '').length;
t.value += '\n' + t2;
setCursorPosition(t, l, l);
function setCursorPosition(oInput, oStart, oEnd) {
if( oInput.setSelectionRange ) {
else if( oInput.createTextRange ) {
var range = oInput.createTextRange();
<form action="#" onsubmit="return false;">
<textarea name="bob" cols="50" rows="5">Some Stuff Here Already</textarea><br>
<input type="button" value="add" onclick="add(this, 'bob', 'Text_1', 'Text_2');">

08-07-2008, 11:31 PM
and how do you get the cursor position?

08-08-2008, 01:31 AM
and how do you get the cursor position?

In the above example, it is this line:

l = t.setSelectionRange? t.value.length : t.value.replace(/\n/g, '').length;

08-08-2008, 04:17 AM
ok that woks right as i need it to there is just one thing that i can not figure out. I know i am a noob.

if i need to add 2 buttons, one that has the possibility of adding text inside the other how would i go about doing that. I do not know any javascript sorry.

Thanks in advance for the help.