views:

226

answers:

1

Hey

Is is possible to trigger a link to select a single line inside textarea. If it is, how?

Martti Laine

A: 

A similar problem is described here.

In summary, if you know the starting and ending index (or the starting and ending values):

<script type="text/javascript">

    function createSelection(field, start, end) {
        if (field.createTextRange) {
            var selRange = field.createTextRange();
            selRange.collapse(true);
            selRange.moveStart('character', start);
            selRange.moveEnd('character', end - start);
            selRange.select();
        } else if (field.setSelectionRange) {
            field.setSelectionRange(start, end);
        } else if (field.selectionStart) {
            field.selectionStart = start;
            field.selectionEnd = end;
        }
        field.focus();
    }

    function select() {

        var textArea = document.getElementById('one');

        var startIndex = textArea.value.indexOf("help");
        var endIndex = textArea.value.indexOf("do") + "do".length;

        createSelection(textArea, startIndex, endIndex);
    }

</script>

<a href="#" onclick="select();">Select Text</a>
<br />
<textarea id="one" rows="5" cols="25">Please help me do this!</textarea>

To retrieve the value of the selected text, I would recommend jquery-fieldselection [http://github.com/localhost/jquery-fieldselection]

Doc Hoffiday
Hey, thanks for the answer, but wanna tell me, how to get the start and end of row? :)
Martti Laine
You could set 'wrap="off"' on the textarea and then split the rows by the newline ('\n') character.
Doc Hoffiday