JSFiddle - React, Tailwind, and code Playground
HTML
<table>
<tr>
<td>
<textarea id="myTxt" onmouseup="getRange();" onkeyup="getRange();">
123456789
1234
123456789
</textarea>
</td>
<td>
<input type="button" value="<< Set Caret/Selection" onclick="setRange();" />
</td>
<td>
<div>
Start:
</div>
<input type="text" id="inpStart" /><br />
<div>
End:
</div>
<input type="text" id="inpEnd" />
<div>
Text To Insert:
</div>
<input type="text" id="insTxt" />
<br /><br />
<div>
Caret position after insertion:
</div>
<div>Before:<input type="radio" name="insPos" value="before" checked="on"></div>
<div>After:<input type="radio" name="insPos" value="after"></div>
<div>Select Insertion:<input type="radio" name="insPos" value="select"></div>
</td>
</tr>
<tr>
<td colspan="3">
<b>Note:</b>
Select text in textarea using keyboard/mouse, start & end position of selection should show up in fields.<br/>
Populate start and end fields and click the button to set caret position or select text.<br/>
Populate start,end, insert and position fields to replace selected text and place caret/selection as selected in radio button options.
Entering same value in both Start and End fields will set the caret position instead of highlighting a text selection.
</td>
</tr>
</table>
CSS
textarea
{
width: 300px;
height: 300px;
}
table
{
width: 600px;
}
JavaScript
$.fn.extend({
// Gets or set caret or selection of text in an input field based on options {start:??,end:??}
caretSelection : function(options)
{
// If start,end are provided make a setter call
if(options && !isNaN(options.start) && !isNaN(options.end))
{
this.setCaretSelection(options);
}
// if start,end not provided, make getter call
else
{
return this.getCaretSelection();
}
},
// Sets caret position or highlights text to select it within an input field
setCaretSelection : function(options)
{
var inp = this[0];
// Set the selection for IE only, fairly simple - feature detection
if(inp.createTextRange)
{
// Creat a blank text range
var selRange = inp.createTextRange();
// Collapse any existing selection and move the caret to the beginning
selRange.collapse(true);
// Move caret to the starting position and start highlighting
selRange.moveStart('character', options.start);
// Move to the right equivalent to the number of characters we need to select
selRange.moveEnd('character',options.end - options.start);
// Highlight the selection
selRange.select();
}
// Set the selection for all other nicer browsers - feature detection
else if(inp.setSelectionRange)
{
inp.focus();
inp.setSelectionRange(options.start, options.end);
}
},
// Returns start and end position of selection when text in an input field is selected
getCaretSelection: function()
{
var inp = this[0], start = 0, end = 0;
// For all other browsers than IE, nice and easy - feature detection
if(!isNaN(inp.selectionStart))
{
start = inp.selectionStart;
end = inp.selectionEnd;
}
// For IE only,...