Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
90
rated 0 times [  94] [ 4]  / answers: 1 / hits: 23684  / 12 Years ago, fri, november 30, 2012, 12:00:00

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.


More From » jquery

 Answers
7

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/


[#81684] Thursday, November 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dayana

Total Points: 302
Total Questions: 102
Total Answers: 100

Location: Cayman Islands
Member since Fri, Mar 4, 2022
2 Years ago
dayana questions
Sun, Apr 4, 21, 00:00, 3 Years ago
Fri, Aug 21, 20, 00:00, 4 Years ago
Fri, Aug 21, 20, 00:00, 4 Years ago
;