1

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
    }
});
Kyle Noland
  • 4,788
  • 6
  • 30
  • 33
  • Try adding a listener to your model for the backgrid:editing event. I think the fourth parameter of the callback is a reference to the input field which is generated when the cell becomes editable. You could probably use jquery select to select the text in the field. – net.uk.sweet Sep 16 '13 at 23:42
  • @net.uk.sweet, could you give me an example of how to do that? Frankly I'm not very familiar with Backgrid or Backbone, and I don't really have the time to learn it right now, I just need this quick functionality in place. – Kyle Noland Sep 17 '13 at 01:56

1 Answers1

1

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;
      }
    })
});
Kyle Noland
  • 4,788
  • 6
  • 30
  • 33