Tabbing outside of handsontable cells

2019-08-10 05:29发布

问题:

We have a button at the bottom of handsontable. When the user tabs in the last cell, can we select the button instead of wrapping back to the first cell?

Here is the jsFiddle

var data = [
  ["", "Ford", "Volvo", "Toyota", "Honda"],
  ["2014", 10, 11, 12, 13],
  ["2015", 20, 11, 14, 13],
  ["2016", 30, 15, 12, 13]
];

var container = document.getElementById('example');
var hot = new Handsontable(container, {
  data: data,
  minSpareRows: 1,
  rowHeaders: true,
  colHeaders: true,
  autoWrapRow: true,
  autoWrapColumn: true
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/handsontable/0.14.1/handsontable.full.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handsontable/0.14.1/handsontable.full.js"></script>
<form>
  <div id='example'></div>
  <br />
  <input type="button" value="Save"></input>
</form>

回答1:

What I would do is capture the event, in your case .on('beforekeydown'), and check for the tab key. If pressed, check what cell the hot instance is currently on using hot.getSelected() and if it is the last cell, switch the focus to whatever button you want. Here is some detail of the code:

Handsontable.Dom.addEvent(containerTag, 'keydown', function(e) {
  // On Tab, go to external button if last cell
  if (e.keyCode === 9 && hotInstance) {
    e.stopPropagation();
    var selection = hotInstance.getSelected();
    var rowIndex = selection[0];
    var colIndex = selection[1];
    if (rowIndex == lastRow && colIndex == lastCol) {
       hotInstance.deselect();
       buttonJquerySelector.focus();
    }
  }
});

I haven't tested this code but this is more or less what you should be trying to do.