dimanche 28 juin 2015

Replace text on every selected line in a textarea

I have a textarea in my HTML where users can type something. There is a button near the textarea that adds a ' - ' to the beginning of a selected line to make it like a list.

For example if I have the following text:

This is a line of text

And I selected it all and pressed the button it would appear like this:

- This is a line of text

However, this only works when selecting one line. If I was to select two lines, it will only format the one line. Here is my code:

Javascript with some jQuery:

var selection = $("#answer" + questionNumber).getSelection();
if (selection.text != '') {
    $("#answer" + questionNumber).replaceSelectedText('  - ' + selection.text);
    return;
}

The .getSelection() and .replaceSelectedText() methods come from this jQuery plugin.

I though maybe by identifying if there are '\n' in the selection then adding the list styling to it, perhaps using regex, though I'm not sure how to go about coding that.

Here is a JSFiddle of my issue.

Aucun commentaire:

Enregistrer un commentaire