Ext.form.TextField.prototype.getSelection = function() {
var domElement = this.getEl().dom;
if (Ext.isIE){
var sel = document.selection;
var range = sel.createRange();
if (range.parentElement()!=domElement) return null;
var bookmark = range.getBookmark();
var selection = domElement.createTextRange();
selection.moveToBookmark(bookmark);
var before = domElement.createTextRange();
before.collapse(true);
before.setEndPoint("EndToStart", selection);
var after = domElement.createTextRange();
after.setEndPoint("StartToEnd", selection);
return {
selectionStart: before.text.length,
selectionEnd: before.text.length + selection.text.length,
beforeText: before.text,
text: selection.text,
afterText: after.text
}
} else {
if (domElement.selectionEnd && domElement.selectionStart) {
if (domElement.selectionEnd > domElement.selectionStart){
return {
selectionStart : domElement.selectionStart,
selectionEnd : domElement.selectionEnd,
beforeText : domElement.value.substr(0, domElement.selectionStart),
text : domElement.value.substr(domElement.selectionStart, domElement.selectionEnd - domElement.selectionStart),
afterText : domElement.value.substr(domElement.selectionEnd)
};
}
}
}
return null;
}
Ext.form.TextField.prototype.getSelectedText = function() {
var selection = this.getSelection();
return selection==null?null:selection.text;
}
Unfortunately Internet Explorer and Firefox give us a hard time by implementing the functionality of getting the selection so different; this small listing gives us a getSelection() function returning a JS object very similar to the one Firefox returns, and adapts to IE accordingly. This object can be used to treat not just the selection itself, but the text before and after as well.The getSelectedText() method returns the selection simply as a text.