5

I want to indent the selected text in a <textarea> by 4 spaces, just like StackOverflow does for code, using jQuery. I'm doing this to create a text editor similar to SO's, but with only basic functionality.

I don't want links or suggestions to ready-made editors; I've got everything I want but my problem above. Can someone give me some pointers as to how I'd indent the selected text, or some code snippets?

Thanks.

Bojangles
  • 99,427
  • 50
  • 170
  • 208

2 Answers2

5
function indentSelection() {
    var selection = $(this).getSelection().text;
    var textarea = $(this);
    var result = '';
    var lines = selection.split('\n');
    var space = '    ';
    for(var i = 0; i < lines.length; i++)
    {
        result += space + lines[i] + '\n';
    }
    var new_text = textarea.val().split(selection).join(result);
    textarea.val(new_text);
}

Should do it. For an example on how to acquire the selected text (this has been shortened here) see How to get selected text in textarea?

Community
  • 1
  • 1
marc
  • 6,103
  • 1
  • 28
  • 33
  • Thanks very much marc. The issue I'm having now is that `window.getSelection()` and friends (here: http://mark.koli.ch/2009/09/use-javascript-and-jquery-to-get-user-selected-text.html) wont't select the text inside my textarea. – Bojangles Jul 16 '11 at 16:09
  • Oops. No worries - it's all sorted now thanks to this jQuery plugin: https://github.com/localhost/jquery-fieldselection. Thansk very much for your help nonetheless - I would be nowhere without this starting point. – Bojangles Jul 16 '11 at 16:13
  • It appears I spoke too soon. I've got two problems: 1) A newline is added after the end of the indented selection and, more importantly, 2) I can't indent selected text that was typed in, I can only indent text that was either added by JS or was in the textarea at the start. – Bojangles Jul 16 '11 at 16:24
  • Could you set up an example on jsFiddle? – marc Jul 16 '11 at 16:26
  • Of course :-) First, try just selecting the text already there; it indents fine, but with a spare newline after it. Now if you type _anything_ at all into the textbox, it no longer works. No errors are output. http://jsfiddle.net/jamwaffles/zvqy5/ – Bojangles Jul 16 '11 at 16:30
  • Updated it, I had to use val() instead of text(), because text() is always how it has been initialized. see http://jsfiddle.net/zvqy5/22/ – marc Jul 16 '11 at 17:00
  • Thank you so very much marc. I noticed the `/22` at the end of the JSFiddle URL - thanks for the effort! – Bojangles Jul 16 '11 at 17:05
1

I'd use a regex replace() for this. Just replace the new-line with a new-line plus four spaces:

function indentSelection(textarea) {
  $(textarea).val(
        $(textarea).val().substring(0, textarea.selectionStart)
          + $(textarea).getSelection().text.replace(/\n/m,'    \n')
          + $(textarea).val().substring(textarea.selectionEnd)
   );
}
Spudley
  • 166,037
  • 39
  • 233
  • 307