I'm been searching for a script to insert a string in a textarea at the cursor position. I came across the following script by Tim Down. Can someone help me to implement it in my case.
I have a list of SPANs that are generated dynamically. When a user clicks on a SPAN I want the content to be inserted in the textarea at the cursor position and add a question mark at the beginning of the inserted string:
<span class="spanClass" id="span1">String1</span>//onclick insert String1 into teaxarea as ?String1
<span class="spanClass" id="span2">String2</span>//onclick insert String2 into teaxarea as ?String2
<span class="spanClass" id="span3">String3</span>//onclick insert String3 into teaxarea as ?String3
<span class="spanClass" id="span4">String4</span>//onclick insert String4 into teaxarea as ?String4
<span class="spanClass" id="span5">String5</span>//onclick insert String5 into teaxarea as ?String5
<span class="spanClass" id="span6">String6</span>//onclick insert String6 into teaxarea as ?String6
...
<textarea id="spanString"></teaxtarea>
function insertTextAtCursor(el, text) {
var val = el.value, endIndex, range;
if (typeof el.selectionStart != "undefined" && typeof el.selectionEnd != "undefined") {
endIndex = el.selectionEnd;
el.value = val.slice(0, el.selectionStart) + text + val.slice(endIndex);
el.selectionStart = el.selectionEnd = endIndex + text.length;
} else if (typeof document.selection != "undefined" && typeof document.selection.createRange != "undefined") {
el.focus();
range = document.selection.createRange();
range.collapse(false);
range.text = text;
range.select();
}
}
How can I implement Tim's Javascript into my codes??? Or is there another way to accomplish this task??? Thanks.