How to select line of text in textarea
Asked Answered
A

5

11

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.

Allegedly answered 30/11, 2012 at 17:55 Comment(2)
By the way, everything is contained on a single page. No 'submits' or anything.Allegedly
start here #647111 or here #1712917 then you need to work out how your parse button (no code supplied) knows where the selection should beCampagna
P
30

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/

Pasquale answered 30/11, 2012 at 18:33 Comment(6)
That is spectacularly fantastic. Thank you so much!Allegedly
If for some reason you find yourself needing to deselect any selection: window.getSelection().removeAllRanges()Enphytotic
I have no idea why but the jsfiddle is not selecting the line text, it is not working.Rewire
@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.Osterhus
@HimanshuTanwar Yes, I added jquery instead of mootools and it worked, thank you.Rewire
@lostsorce how we can change the background colour of the selected text?Cottar
R
5

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
Reading answered 14/1, 2021 at 15:54 Comment(1)
The last line can't be selected with this function. When you try to do that, the cursor jumps to the beginning of textarea.Corrigan
C
4

Add a onclick or ondblclick event handler to your <textarea>:

<textarea onclick="onClickSelectLine(this)"></textarea>

And JavaScript function to handle the onclick event:

/**
 * onclick event for TextArea to select the whole line
 * @param textarea {HTMLTextAreaElement}
 * @returns {boolean}
 */
function onClickSelectLine(textarea) {
    if (typeof textarea.selectionStart == 'undefined') {
        return false
    }
    let text = textarea.value
    let before = text.substring(0, textarea.selectionStart)
    let after = text.substring(textarea.selectionEnd, text.length);
    let startPos = before.lastIndexOf("\n") >= 0 ? before.lastIndexOf("\n") + 1 : 0
    let endPos = after.indexOf("\n") >= 0 ? textarea.selectionEnd + after.indexOf("\n") : text.length
    textarea.selectionStart = startPos
    textarea.selectionEnd = endPos
    return true
}
Candiscandle answered 14/6, 2014 at 19:27 Comment(2)
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;Cispadane
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?Prisage
V
0

To make the function more forgiving on possible faulty input add after:

// array starts at 0
lineNum--;

This code:

if (typeof(tarea) !== 'object' || typeof(tarea.value) !== 'string') {
  return false;
}

if (lineNum === 'undefined' || lineNum == null || lineNum < 0) {
  lineNum = 0;
}
Virgil answered 10/5, 2019 at 22:9 Comment(0)
M
-1

How to select line of text in textarea javascript double click on particular line.

//This function expects first parameter to be reference to your textarea. 
function ondblClickSelection(textarea){
    var startPos = 0;
    var lineNumber = 0;
    var content = "";
    if(typeof textarea.selectionStart == 'undefined') {
        return false;
    }
    startPos = textarea.selectionStart;
    endPos = textarea.value.length;
    lineNumber = textarea.value.substr(0,startPos).split("\n").length - 1;
    content = textarea.value.split("\n")[lineNumber];
    var lines = textarea.value.split("\n");
    var endPos = lines[lineNumber].length+startPos;
    textarea.selectionStart = startPos;
    textarea.selectionEnd = endPos;
    return true; 
}
Militia answered 25/7, 2013 at 11:11 Comment(1)
The idea is good but the code has a bug and allocates a lot of memory for the array of lines. Instead use the function from https://mcmap.net/q/957876/-how-to-select-line-of-text-in-textareaDitmore

© 2022 - 2024 — McMap. All rights reserved.