Insert into textarea | JavaScript
I'm trying to insert the image url where the point of the is to be when editing the textarea value.
function addImageURL()
{
var imageurl = prompt("Enter image URL", "Your name")
var post = document.getElementById("message-put").value;
document.getElementById('message-put').value = 开发者_如何学Pythonpost + '[img]' + imageurl + '[/img]';
}
This code grabs the value inside the adds the image url next to it which I don't want, I need it to insert it where the point was when editing the textarea
Thanks
EDIT:
Like Stackoverflow, you see the image icon, you click it or click on the hyperlink, a box comes up and inserts it where you were editing the textarea :P
If you want to insert something at the cursor, here is something I found using teh Googlez:
function insertAtCaret(areaId, text) {
var txtarea = document.getElementById(areaId);
var scrollPos = txtarea.scrollTop;
var strPos = 0;
var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
if (br == "ie") {
txtarea.focus();
var range = document.selection.createRange();
range.moveStart('character', -txtarea.value.length);
strPos = range.text.length;
} else if (br == "ff") strPos = txtarea.selectionStart;
var front = (txtarea.value).substring(0, strPos);
var back = (txtarea.value).substring(strPos, txtarea.value.length);
txtarea.value = front + text + back;
strPos = strPos + text.length;
if (br == "ie") {
txtarea.focus();
var range = document.selection.createRange();
range.moveStart('character', -txtarea.value.length);
range.moveStart('character', strPos);
range.moveEnd('character', 0);
range.select();
}
else if (br == "ff") {
txtarea.selectionStart = strPos;
txtarea.selectionEnd = strPos;
txtarea.focus();
}
txtarea.scrollTop = scrollPos;
}
The source: http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/ (I haven't tested this; it's from 2008 so it may be a little dated).
A technique I used when trying to achieve similar functionality in a WYSIWYG:
Retrieve parent node from selection (range) in Gecko and Webkit » StackOverflow
Might be useful if working with frames, or want to avoid some cursor issues I ran into.
I think you may find what you're looking for here:
Caret position in textarea, in characters from the start
And an example implementation here:
http://javascript.nwbox.com/cursor_position/
精彩评论