Cybercampbell
Cybercampbell

Reputation: 2606

jQuery split textarea content into two textareas at a particular line number

I need to split textarea content into two textareas at a particular line number of the content using jQuery. Can this be done?

I googled but couldn't find anything. jQuery's pretty powerful, I would have thought this can be done.

Any help with this is very much appreciated.

C

Upvotes: 1

Views: 869

Answers (1)

CJ Ramki
CJ Ramki

Reputation: 2630

try this code,

<select id='lineSelector'>
    <option>- select line -</option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
</select>
<br/>
<textarea id='tarea' cols='40' rows='5'>first line second line third fourth fifth</textarea>
<textarea id="newarea" cols="40" rows="5"></textarea>

javascript code,

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 final = tarea.value.substring(startPos, endPos);
tarea.value = tarea.value.replace(final,"");
}

/// debugging code
var sel = document.getElementById('lineSelector');
var tarea = document.getElementById('tarea');
sel.onchange = function () {
    selectTextareaLine(tarea, this.value);
}

SEE FIDDLE DEMO

Upvotes: 2

Related Questions