views:

1748

answers:

3

I have a page with a lot of textboxes. When someone clicks a link, i want a word or two to be inserted where the cursor is, or appended to the textbox which has the focus.

For example, if the cursor/focus is on a textbox saying 'apple' and he clicks a link saying '[email]', then i want the textbox to say, 'apple [email protected]'.

How can I do this? Is this even possible, since what if the focus is on a radio/dropdown/non textbox element? Can the last focused on textbox be remembered?

A: 

you can only focus required textbox an insert the text there. there is no way to find out where focus is AFAIK (maybe interating over all DOM nodes?).

check this stackoverflow - it has a solution for you: http://stackoverflow.com/questions/497094/how-do-i-find-out-which-javascript-element-has-focus

dusoft
+7  A: 

Use this, from here:

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;
}

Usage:

<textarea id="textareaid"></textarea>
<a href="#" onclick="insertAtCaret('textareaid','text to insert');return false;">
gclaghorn
+1  A: 

I think you could use the following JavaScript to track the last-focused textbox:

<script>
var holdFocus;

function updateFocus(x)
{
    holdFocus = x;
}

function appendTextToLastFocus(text)
{
    holdFocus.value += text;
}
</script>

Usage:

<input type="textbox" onfocus="updateFocus(this)" />
<a href="#" onclick="appendTextToLastFocus('textToAppend')" />

A previous solution (props to gclaghorn) uses textarea and calculates the position of the cursor too, so it may be better for what you want. On the other hand, this one would be more lightweight, if that's what you're looking for.

DreadPirateShawn
Good idea. I used jquery so each textbox which had a certain class had this event applied to them rather than having to put "onfocus=..." in the html of each textbox. But good approach :)
Click Upvote