Search code examples
jquerybackbone.jsbackgrid

How do I automatically select text in a Backgrid cell when it receives focus?


I have an app that is using BackgridJS for a spreadsheet-like editor interface. As the user tabs across a row, each cell (Backgrid.StringCell) becomes editable automatically. However, the cursor is placed at the end of the cell contents requiring the user to backspace their way to the beginning of the string before entering new data into the cell.

I would like cell content to automatically be highlighted when a cell receives focus so that the user can immediately begin entering new data into that cell, or tab to the next cell to leave that data in place.

I have a feeling I should be listening to the enterEditMode event of the StringCell, but I can't figure out where to go from there. I currently have:

var stringCell = Backgrid.StringCell.extend({
    enterEditMode: function() {
        // highlight cell contents here
    }
});

Solution

  • With a point in the right direction from the BackgridJS author, I was able to come up with this solution:

    var decimalFormatter = {
      fromRaw: function (rawData) {
        if(rawData == 0)
        {
          return '';
        }
    
        return rawData;
      },
    
      toRaw: function(data) {
        return data;
      }
    };
    
    /*
      Create a new custom cell type and set a custom formatter.
      Override the postRender() method in order to automatically select the 
      cell's contents for easier data entry when tabbing across rows.
    */
    
    Backgrid.MyCell = Backgrid.StringCell.extend({
        className: "my-cell",
        formatter: decimalFormatter,
        editor: Backgrid.InputCellEditor.extend({
          postRender: function (model, column) {
            if (column == null || column.get("name") == this.column.get("name")) {
              // move the cursor to the end on firefox if text is right aligned
              if (this.$el.css("text-align") === "right") {
                var val = this.$el.val();
                this.$el.focus().val(null).val(val).select();
              }
              else {
                this.$el.focus().select();
              }
            }
    
            return this;
          }
        })
    });