In a recent project (where I wrote some keypress input filter code, to filter to numeric inputs etc) I found that I needed to get the selected text in an input, so that I knew I didn't have to Event.stop the keypress as it would overwrite the selection anyway.
In another area in the same control library, I needed to get/set the text caret position, to allow me to detect when the caret was getting close to a maximum input length and 'jump' to the next box.
I found it took quite a bit of searching to locate the correct cross-browser methods of doing these tasks.
I've implemented these methods as standard javascript functions instead of element methods via prototype, though it's on my todo list to do this. They'd be better suited to be on the element themselves.
Without further ado, the code.
Get the selection in a text field
You must pass the element to it, in some browsers, it is not input-dependant, ie: will get the document selection as well.
function getSel(oField)
{
var txt = '';
var foundIn = '';
if (oField.selectionStart)
{
txt = oField.value.substring(oField.selectionStart,oField.selectionEnd);
}
else if (window.getSelection)
{
txt = window.getSelection();
foundIn = 'window.getSelection()';
}
else if (document.getSelection)
{
txt = document.getSelection();
foundIn = 'document.getSelection()';
}
else if (document.selection)
{
txt = document.selection.createRange().text;
foundIn = 'document.selection.createRange()';
}
else
{
return;
}
return txt;
}
Get Caret Pos (for a field)
Gets the caret position within a text input.
function getCaretPos(oField)
{
var iCaretPos = 0;
if (Prototype.Browser.IE)
{
var oSel = document.selection.createRange ();
oSel.moveStart ('character', -oField.value.length);
iCaretPos = oSel.text.length;
}else{
iCaretPos = oField.selectionEnd;
}
return iCaretPos;
}
Set Caret Pos (for a field)
Sets the caret position within a text input.
function setCaretPos(oField, iCaretPos)
{
if (Prototype.Browser.IE)
{
var oSel = document.selection.createRange ();
oSel.moveStart ('character', -oField.value.length);
oSel.moveStart ('character', iCaretPos);
oSel.moveEnd ('character', 0);
oSel.select ();
}else{
oField.selectionStart = iCaretPos;
oField.selectionEnd = iCaretPos;
oField.focus();
}
}
1 comment:
First of all. Thanks very much for your useful post.
I just came across your blog and wanted to drop you a note telling you how impressed I was with the information you have posted here.
Please let me introduce you some info related to this post and I hope that it is useful for community.
Source: Selection methods
Thanks again
Post a Comment