10/20/2009

ExtJS: Getting the selection from a TextField

It is not possible to get the selected text from a TextField in ExtJS 2.2. Fortunately it can easily be solved by introducing a getSelection() method to TextField:
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.


Learning Ext JS

Ext JS 3.0 Cookbook

Ext JS in Action

Professional JavaScript Frameworks: Prototype,YUI, ExtJS, Dojo and MooTools (Wrox Programmer to Programmer)

3 comments:

  1. Nice addition to the TextField classes!

    ReplyDelete
  2. Thanks! I guess getting the selected text from a textbox is not the typical "everyday" problem, but if you need it, you have to dig a bit deeper into ExtJS. Cheers! Lajos

    ReplyDelete