views:

185

answers:

1

If I have a textarea on an HTML page with multiple lines of text in it, how can I most easily append more text to one of those lines (chosen based on user input) using only Javascript?

A: 
var field = document.getElementById('myTextfield');
var textArray = field.value.split("\n");
textArray[3] += "Some text here"; // append some text to 4th line
field.value = textArray.join("\n");

By splitting the text on the \n newline character you get an array of lines. From there, append to any line and join the array with the new line character you previously took out.

Note that this will only work if you insert new lines into the text field. If the text is naturally wrapping, then you will have to do a more complicated character count tactic to divide the lines into your array.

Squeegy