Make full select the text on the single click in text area

The following code sample can be used for to select the all text word in the single click.
Note: This source code is related to comment: Drag ans drop only text of the li into text area.

With the help of this example you can select the text (starting with ‘{‘ and ending with ‘}’) on the single click in the text area. After make full select, you can drag and place anywhere in text area.

[text area in html]

<textarea id="textarea" style="width:500px;height:200px;">Hello {Name}
this is the test message.</textarea>

[JavaScript]

<script type="text/javascript">
 
    var Editor = document.getElementById("textarea");
    Editor.onclick = textarea_Click;
    function textarea_Click() {
        var brac = gettokenPosition(Editor);
        var text = Editor.value;
        var start = brac - 1;
        while (start >= 0) {
            if (text.charAt(start) == '}') return;
            else if (text.charAt(start) == '{') break;
            else start--;
        }
 
        if (start >= 0) {
            var end = brac;
            while (end < text.length) {
                if (text.charAt(end) == '}') break;
                else end++;
            }
 
            if (end < text.length)
                setSelection(Editor, start, end);
        }
    }
 
    function gettokenPosition(el) {
        if (el.selectionStart) {
            return el.selectionStart;
        } else if (document.selection) {
            var r = document.selection.createRange();
            if (r == null) return 0;
            var re = el.createTextRange();
            var rc = re.duplicate();
            re.moveToBookmark(r.getBookmark());
            rc.setEndPoint('EndToStart', re);
            return rc.text.length;
        }
        return 0; 
    }
 
    function setSelection(el, start, end) {
        if ("selectionStart" in el) {
            el.selectionStart = start;
            el.selectionEnd = end + 1;
        } else if (document.selection) {
            var range = el.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end + 1);
            range.moveStart('character', start);
            range.select();
        }
    }
</script>

One thought on “Make full select the text on the single click in text area”

  1. I get emails with dance information. Simple text.
    I have input form that I would like to be able to select specific text and then right click and have all the input choices and the one I pick would be filled with the selected text.
    example of right click menu choices:
    Name
    Event Date
    Age Limit
    Email
    Phone
    URL
    Address Display
    Address Google
    City Google
    State Google
    Comments

Comments are closed.