Here are a few selection helpers I use when working with TextAreas. They are implemented as jQuery extension functions.
selectRange
The first method selectRange
allows you to select a range in an input. It is an adaptation of code found on StackOverflow: http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area
$.fn.extend({
// selects a range in a text area
selectRange: function (start, end) {
if (!end) end = start;
return this.each(function () {
if (this.setSelectionRange) {
this.focus();
this.setSelectionRange(start, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
}
});
It can be used by doing:
$("#mytextarea").selectRange(5,10);
getSelectedRange
This helper will retrieve the currently selected range of an input and will return an object with { start: #num, end: #num }
. It will return the same start and end values if the cursor is positioned on a single character.
Note: it only works for browsers that support selectionStart
and selectionEnd
.
$.fn.extend({
// gets the selected range in the first text area found
// returns hash of { start, end }
getSelectedRange: function() {
var el = this.get(0),
start = 0,
end = 0;
if (el.selectionStart) {
start = el.selectionStart;
end = el.selectionEnd;
}
return {
start: start,
end: end
}
}
});
Usage looks like:
$("#myinput").getSelectedRange();
Which returns something like:
{ start: 5, end: 10 }
getSelectedValue
This helper will retrieve the text of the value that is currently selected. This is useful for getting what the user has highlighted inside the input.
Note: it only works for browsers that support selectionStart
and selectionEnd
.
$.fn.extend({
// gets the selected value for the first text area found
// return the value in the selection
getSelectedValue: function () {
var range = this.getSelectedRange();
var val = this.val();
return val.slice(range.start, range.end);
}
});
Usage looks like:
$("#myinput").getSelectedValue()
replaceSelectedRange
This helper replaces the currently selected range with a supplied content. If a range is not selected, it will insert the content at the current cursor location.
Note: it only works for browsers that support selectionStart
and selectionEnd
.
$.fn.extend({
// replaces the selected range in each text area
// returns an array of affected elements
replaceSelectedRange: function (content) {
return this.each(function () {
var $this = $(this),
range = $this.getSelectedRange(),
start = range.start,
end = range.end,
val = $this.val(),
startText = val.slice(0, start),
endText = "",
replacementLength = content.length;
if (end) {
endText = val.slice(end);
}
$this.val(startText + content + endText);
$this.selectRange(start + replacementLength, start + replacementLength);
});
}
});
Usage looks like:
$("#myinput").replaceSelectedRange('newtext');