Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select line of text in textarea

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.

like image 258
Flat Cat Avatar asked Nov 30 '12 17:11

Flat Cat


1 Answers

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/

like image 101
lostsource Avatar answered Nov 15 '22 14:11

lostsource