This jQuery plugin is for easily finding the starting and ending positions of
selected text in text fields and textareas. It can also be used to set the
selection, and replace the selection with given text (or insert text wherever
the cursor is in the text field or textarea).
Demo
Browser Support
- Chrome
- Firefox
- Microsoft Edge
- yes, even Internet Explorer 5.5+
Include
Include the file directly using <script>
tags:
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script src="jquery-plugins/jquery-textrange.js"></script>
:memo: note: jquery-textrange can be loaded through any
UMD-compatible Javascript
Module Loader.
Methods
You can use this method to get all the information on the selected text of an
element or a specific bit of information.
'get'
Get everything
$('input[name="example"]').textrange('get');
or for short:
$('input[name="example"]').textrange();
This will return a JSON object with the following information:
{
"position":
"start":
"end":
"length":
"text":
}
Get a particular property
This function can also be used to get a particular property of the object.
For example, this will obtain the starting location of the selected text:
var start = $('input[name="example"]').textrange('get', 'start');
'set'
You can use this method to set the starting and ending locations of the
selected text in an element.
It works much like PHP's
substr(), so if you're
familiar with that, it should be a breeze! Here are some examples, anyway.
For the following examples, let's say input[name="example"]
contains the text
abcdef
.
$('input[name="example"]').textrange('set');
$('input[name="example"]').textrange('set', 2);
$('input[name="example"]').textrange('set', 2, 3);
$('input[name="example"]').textrange('set', 2, -2);
$('input[name="example"]').textrange('set', -3);
$('input[name="example"]').textrange('set', -2, 1);
$('input[name="example"]').textrange('set', -4, -1);
If you're looking to set the cursor at one specific location, you can use 0
for length, or you can use $().textrange('setcursor')
(see below).
'setcursor'
You can use this method to set the location of the cursor in your text field.
To set the cursor at the fifth character position:
$('input[name="example"]').textrange('setcursor', 5);
'replace'
You can use this method to replace the selection with given text.
$('input[name="example"]').textrange('replace', 'some text');
There is also an insert
alias for replace
if you're using this method to
insert text at the cursor location. They work the same way.