How to select line of text in textarea

21,658

Solution 1

This function expects first parameter to be reference to your textarea and second parameter to be the line number

function selectTextareaLine(tarea,lineNum) {
    lineNum--; // array starts at 0
    var lines = tarea.value.split("\n");

    // calculate start/end
    var startPos = 0, endPos = tarea.value.length;
    for(var x = 0; x < lines.length; x++) {
        if(x == lineNum) {
            break;
        }
        startPos += (lines[x].length+1);

    }

    var endPos = lines[lineNum].length+startPos;

    // do selection
    // Chrome / Firefox

    if(typeof(tarea.selectionStart) != "undefined") {
        tarea.focus();
        tarea.selectionStart = startPos;
        tarea.selectionEnd = endPos;
        return true;
    }

    // IE
    if (document.selection && document.selection.createRange) {
        tarea.focus();
        tarea.select();
        var range = document.selection.createRange();
        range.collapse(true);
        range.moveEnd("character", endPos);
        range.moveStart("character", startPos);
        range.select();
        return true;
    }

    return false;
}

Usage:

 var tarea = document.getElementById('myTextarea');
 selectTextareaLine(tarea,3); // selects line 3

Working example:

http://jsfiddle.net/5enfp/

Solution 2

The code in the post by darkheir does not work correctly. Based on it I shortened the code and made it working.



    function onClickSelection(textarea){
        if(typeof textarea.selectionStart=='undefined'){
            return false;
        }
        var startPos=(textarea.value.substring(0,textarea.selectionStart).lastIndexOf("\n")>=0)?textarea.value.substring(0,textarea.selectionStart).lastIndexOf("\n"):0;
        var endPos=(textarea.value.substring(textarea.selectionEnd,textarea.value.length).indexOf("\n")>=0)?textarea.selectionEnd+textarea.value.substring(textarea.selectionEnd,textarea.value.length).indexOf("\n"):textarea.value.length;
        textarea.selectionStart=startPos;
        textarea.selectionEnd=endPos;
        return true; 
    }

Solution 3

A somewhat neater version of the search for lines:

    function select_textarea_line (ta, line_index) {

        const newlines = [-1];   // Index of imaginary \n before first line
        for (let i = 0; i < ta.value.length; ++i) {
            if (ta.value[i] == '\n') newlines.push( i );
        }

        ta.focus();
        ta.selectionStart = newlines[line_index] + 1;
        ta.selectionEnd   = newlines[line_index + 1];

    } // select_textarea_line
Share:
21,658
Flat Cat
Author by

Flat Cat

SQL Server database administrator, T-SQL code writer, process streamliner, PowerShell dabbler, PHP and web dev hobbyist.

Updated on January 15, 2021

Comments

  • Flat Cat
    Flat Cat over 3 years

    I have a textarea that is used to hold massive SQL scripts for parsing. When the user clicks the "Parse" button, they get summary information on the SQL script.

    I'd like the summary information to be clickable so that when it's clicked, the line of the SQL script is highlighted in the textarea.

    I already have the line number in the output so all I need is the javascript or jquery that tells it which line of the textarea to highlight.

    Is there some type of "goToLine" function? In all my searching, nothing quite addresses what I'm looking for.

  • Flat Cat
    Flat Cat over 11 years
    That is spectacularly fantastic. Thank you so much!
  • Gabriel
    Gabriel almost 9 years
    your startPos selected also the \n character from previous line, adding +1 to it fixed the job (textarea.value.substring(0, textarea.selectionStart).lastIndexOf("\n") >= 0) ? textarea.value.substring(0, textarea.selectionStart).lastIndexOf("\n") + 1 : 0;
  • Roy Prins
    Roy Prins over 7 years
    If for some reason you find yourself needing to deselect any selection: window.getSelection().removeAllRanges()
  • Amr Elgarhy
    Amr Elgarhy about 6 years
    I have no idea why but the jsfiddle is not selecting the line text, it is not working.
  • Himanshu Tanwar
    Himanshu Tanwar about 6 years
    @AmrElgarhy, It wasn't working for me as well, I removed mootools and it started to work. If you can't remove mootools then replace it with jquery.
  • Amr Elgarhy
    Amr Elgarhy about 6 years
    @HimanshuTanwar Yes, I added jquery instead of mootools and it worked, thank you.
  • Albert F D
    Albert F D over 4 years
    Hello... sorry for reviving this thread. As a complete novice to JS I adapted it to work in an HTA using the onclick event for the textarea element. However it appears to work perfectly well without the if condition, and return statements, under what circumstances are they required?
  • Fadi
    Fadi about 2 years
    @lostsorce how we can change the background colour of the selected text?