0

If a user selects a portion of text, I'd like to extend that selection to the beginning of the first line and to the end of the last line if they select in the middle.

What's the best way to accomplish this?

2
  • 1
    are you working inside an editable region like textarea? Commented Nov 24, 2010 at 21:52
  • Do you mean a selection within a <textarea> or within regular content? Commented Nov 25, 2010 at 0:34

1 Answer 1

2

Use setSelectionRange(beg, end) or selectionStart/selectionEnd to change the selection. Basically from current selection range, you try to get the index (start, end) of the span indices you're trying to select and then change the selection. Assuming you want to wrap/extend the selection to nearest "NEWLINE"s, here's a sample code:

 var x = $("#input input:first")[0]; var value = x.value; var NEWLINE = '\n'; // whatever is your newline delimiter. var start = value.substr(0, x.selectionStart).lastIndexOf(NEWLINE); if (start == -1) start = 0; var end = value.substr(x.selectionEnd).indexOf(NEWLINE); if (end == -1) end = value.length;

x.setSelectionRange(start, end); or x.selectionStart = start, x.selectionEnd = end;

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.