Hi! How can I indent each line of the selected text in a textarea control using JavaScript. Something similar to the Code Sample button of the Stack Overflow's editor.
UPDATE: Viewing the code of And, I wrote a solution, but only works with Firefox (also).
The functions is:
function indentSelection() {
var selection, newValue;
var txt = document.getElementById("txt");
var start = txt.selectionStart;
var end = txt.selectionEnd;
// extend the selecction start until the previous line feed
start = txt.value.lastIndexOf("\n", start);
// if there isn't a line feed before,
// then extend the selection until the begging of the text
if (start == -1) {
start = 0;
}
// if the selection ends with a line feed,
// remove it from the selection
if (txt.value.charAt(end - 1) == "\n") {
end = end - 1;
}
// extend the selection end until the next line feed
end = txt.value.indexOf("\n", end);
// if there isn't a line feed after,
// then extend the selection end until the end of the text
if (end == -1) {
end = txt.value.length;
}
// move the selection to a new variable
selection = txt.value.substring(start, end);
// add four spaces before line feeds
selection = selection.replace(/^(?=.+)/mg, " ");
// rebuild the textarea content
newValue = txt.value.substring(0, start);
newValue += selection;
newValue += txt.value.substring(end);
txt.value = newValue;
}
An example could be:
<textarea id="txt" cols="80" rows="8">bla bla bla
bla bla bla
bla bla bla
bla bla bla</textarea>
<a href="#" onclick="indentSelection();return false;">indent selection!</a>