11/04/2013

[ExtJS] Partially Select Text in textfield Programmatically

We are trying to build a FTP client via ExtJS.
When users want to create a new folder on the ftp server, we'd like to pop a form which contains a path input text field. The default value of path field is set as {current_foder}/New_Folder. While New_Folder is the default new folder name, of course, it could be modified by user before submitting.
In this case, selecting the text "New_Folder" automatically makes user change the new folder name by just typing a new name without selecting  by themselves.
Partially Select Text in textfield 
Here is implementation for selecting a a portion of a text in textfield programmatically in ExtJS.
Ext.define('Ext.enhance.form.field.Text', {
   override: 'Ext.form.field.Text',
   selectText: function (start, end) {
      var field = this.inputEl.dom;
      if (field.createTextRange) {
         var selRange = field.createTextRange();
         selRange.collapse(true);
         selRange.moveStart('character', start);
         selRange.moveEnd('character', end);
         selRange.select();
      } else if (field.setSelectionRange) {
         field.setSelectionRange(start, end);
      } else if (field.selectionStart) {
         field.selectionStart = start;
         field.selectionEnd = end;
      }
      field.focus();
   }
});
Ext.define('TonyTuan.CreateFolderWin', {
   extend: 'Ext.window.Window',
   width: 300,
   layout: {
      type: 'fit'
   },
   title: 'Window',
   initComponent: function () {
      var me = this;
      // set focus before call selectText()
      me.defaultFocus = 'path';
      me.items = [{
         xtype: 'form',
         bodyPadding: 10,
         layout: 'anchor',
         defaultType: 'textfield',
         items: [{
            fieldLabel: 'path',
            name: 'path',
            itemId: 'path'
         }]
      }];
      me.callParent();
      me.on({
         // set default value for path
         show: function () {
            me.down('#path').setValue('folder1/New_Folder');
            me.down('#path').selectText(6, 18);
         }
      });
   }
});
Note that setting defaultFocus properly in Window makes users be able to enter text in field without clicking on the filed.