views:

288

answers:

3

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 = post + '[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

alt text

A: 

I think you may find what you're looking for here:

http://stackoverflow.com/questions/263743/how-to-get-cursor-position-in-textarea

And an example implementation here:

http://javascript.nwbox.com/cursor_position/

marapet
A: 

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).

Vivin Paliath
A: 
Jason