Skip to content

Row selection and keyboard ​

Set the selection option to let users pick rows. They can click a row or a checkbox, move between cells with the arrow keys, and press Space to select. Filter by department in the grid and watch the counts. Rows the filter hides stay selected.

Live demo — drawn by the real renderer

Turn on row selection ​

Pass a string for the mode. Use an object when you also want a checkbox column. The default is 'none', so nothing is selectable until you set it.

ts
const options = {
  columns,
  rows,
  rowKey: 'id',
  selection: { mode: 'multiple', checkbox: true },
};
ModeBehavior
'none'Rows cannot be selected
'single'One row at a time. Checkboxes behave like radio buttons
'multiple'Many rows. The string 'multiple' alone gives no checkbox column

With checkbox: true, the checkbox column sits right after the row-number column. The header checkbox selects or clears all visible rows, and shows a mixed state when only some are selected.

Select with the mouse ​

ActionResult
Click a rowSelects only that row
Ctrl+click (Cmd on Mac)Toggles that row
Shift+clickSelects the range from the last selected row to the clicked row
Click a checkboxToggles that row. No Ctrl needed
Shift+click a checkboxAdds the range from the last selected row

In single mode, Shift+click acts like a plain click. Use Ctrl+click or the checkbox to clear the selection.

Select a cell range by touch ​

Since 1.8.0

The option touchRangeSelect (default true) is available from 1.8.0. It only applies with cellSelection: 'multiple'.

On a touch screen a finger drag scrolls the grid, so you cannot drag out a range like with a mouse. Instead, press a cell for 0.5 s to enter range mode.

  1. Hold a cell for 0.5 s: its outline pulses once (no vibration is used) and the cell is selected. From then on moving the finger does not scroll the grid.
  2. The range grows towards the finger. At an edge the grid scrolls and the range keeps growing.
  3. Lift the finger to finish. The range stays, so you can copy it, make a chart from it or fill it.
  4. While a range exists, a round handle sits on the corner of its last cell (touch screens, when there is no fill handle). Drag the handle to grow or shrink the range right away.
  • A short drag (more than 10 px of movement) is a scroll as before. A mouse or a pen is not affected.
  • Lifting without dragging fires cellLongPressed and opens the cell menu, like the old long-press.
  • A long-press inside an already selected block of cells starts moving cells (cellDrag), not range mode.
  • With reduced motion the pulse is a short steady outline.
  • Turn it off with touchRangeSelect: false. Then a touch long-press only opens the cell menu.
ts
createGrid(el, { columns, rows, rowKey: 'id', cellSelection: 'multiple' }); // touch range selection is on by default
createGrid(el, { columns, rows, rowKey: 'id', cellSelection: 'multiple', touchRangeSelect: false });

Drag a cell range ​

Since 1.4.0

The cellDrag option, the column cellDraggable, the events cellsDragStarted, cellsDragCancelled and cellsDropped, and the hooks beforeCellsDrag and beforeCellsDrop are available since 1.4.0. In the modular bundles you need the drag bundle (maxgrid/drag, maxgrid.drag.min.js).

Drag a cell range you have already selected to move or copy it to a rectangle of the same size. It needs cellSelection: 'multiple' and, because it writes values, the editing bundle. It is off by default.

ts
createGrid(el, {
  columns: [
    { id: 'name', editable: true },
    { id: 'memo', editable: true, cellDraggable: false }, // cells of this column can be neither dragged nor dropped onto
  ],
  cellSelection: 'multiple',
  cellDrag: true, // same as { mode: 'move' }. { mode: 'copy' } is also available
  hooks: {
    beforeCellsDrop: ({ from, to, mode, values }) => true, // false drops nothing
  },
});
ItemContent
StartPress inside the range and drag (mouse 4px, touch 400ms)
Outside, ShiftRange selection
Drop positionCell under the pointer = top-left of a same-size rectangle (dashed mark)
'move'Clears source cells that are not covered
'copy'Keeps the source
Ctrl (Cmd)Hold at drop for the other mode
Outside the tableCancelled (invalid-target)
EdgesAuto-scroll
CancelEsc, losing window focus, pointer cancel
WritingSame checks as editing, one undo step
Cells not writtenReported in rejected with a reason
After the dropSelection = the dropped rectangle
  • Start: press inside a range you already selected and drag. Pressing outside, or with Shift, is range selection as before. The selection stays.

  • Move: source cells that the new values do not cover are cleared like the Delete key. A source cell whose target write was refused is not cleared, so no value is lost.

  • Writing: goes through editable, locked, validation and beforeEdit, and the whole drop is one undo step.

  • Cells not written: read-only, locked, cellDraggable: false, failing validation, or covering part of a merged range. They are not written and come back in rejected with a reason.

  • Touch: while you long-press, neither the cell menu nor the browser menu opens.

  • rejected in cellsDropped is a list of { rowKey, columnId, reason }. reason is a word such as not-draggable, merge, not-data, or a validation message.

  • count in cellsDropped is the number of target cells written. Source cells cleared by a move are not counted (moving a 2×2 range gives 4).

  • A merged cell can be dropped only when its whole range is inside the rectangle. The rule that clears the leftover values of a merged range (nullMergeOthersByDrop) does not exist.

  • The keyboard alternative is cut and paste (Ctrl+X, Ctrl+V) (Clipboard).

  • Dragging whole rows is a different feature: use rowDrag in 1.4.0.

Fill handle ​

Since 1.4.0

The cellFill option, the column fillable, the fillRange API, the events fillStarted and fillEnded, the hook beforeFill and the keys Ctrl+D and Ctrl+R are available since 1.4.0. In the modular bundles you need the drag bundle.

Drag the small square (the fill handle) at the end of a selected range to fill down or right. It needs cellSelection and the editing bundle, and is off by default.

ts
createGrid(el, {
  columns: [
    { id: 'month', kind: 'number', editable: true },
    { id: 'memo', editable: true, fillable: false }, // a fill never writes this column
  ],
  cellSelection: 'multiple',
  cellFill: true, // same as { direction: 'both', clearOnShrink: true }
  cellFill: { direction: 'y', fill: (ctx) => undefined }, // lock the direction, or fill yourself
});

api.fillRange(
  { from: { rowKey: 1, columnId: 'month' }, to: { rowKey: 2, columnId: 'month' } }, // source
  { from: { rowKey: 1, columnId: 'month' }, to: { rowKey: 10, columnId: 'month' } }, // target (must contain the source)
);
ItemContent
When the handle showsOne selected range + a fillable column (end corner cell)
DirectionThe axis moved more ('x', 'y' lock it)
Default ruleRepeat; a series for two or more numbers with a constant step
DecimalsRounded to 10 places (editorParams.decimals first)
ShrinkingClears the cells that leave (kept with clearOnShrink: false)
fill callbackReturns the values of the part outside the source
Ctrl+D, Ctrl+RFill the first row or column over the whole range
WritingSame checks as editing, one undo step
Cells not filledReported in rejected with a reason
CancelEsc, losing window focus, pointer cancel
  • Direction: the axis along which the pointer moved more pixels, not the number of cells crossed.

  • When filling right or left into a column of another kind, the value is read as text like a paste. If it cannot be read it is refused as type-mismatch.

  • fill callback: receives { source, sourceRange, targetRange, direction, columns } and returns the values of the part outside the source (rows × columns). undefined, a wrong shape or a thrown error falls back to the default rule; a throw is reported as an error event.

  • Cells not filled: fillable: false, read-only or locked (not-editable), failing validation (the message), covering part of a merged range (merge), group and summary lines (not-data), kind mismatch (type-mismatch).

  • Touch: you can grab and drag the handle (16px on touch screens).

  • The fillRange target must contain the source and extend it along one axis only; otherwise it is an invalid-option before any state changes. Extending up or left continues the series backwards. opts.direction must match the target.

  • The event fillEnded carries { source, target, direction, count, rejected }. If the hook beforeFill({ sourceRange, targetRange, direction }) returns false, nothing is written and no event is emitted.

  • The fill handle can be used together with cell dragging (cellDrag). The handle is outside the cell body, so it receives the press first.

Move between cells with the keyboard ​

Click the grid or Tab into it, and the focused cell gets an outline. Arrow keys move the focus without changing the selection. Focus and selection move independently, as in a spreadsheet.

KeyAction
← ↑ → ↓Move one cell. Stops at the edge
Tab, Shift+TabNext or previous cell. At a row end, wraps to the next or previous row. Past the last cell, focus leaves the grid
Home, EndFirst or last column of the current row
Ctrl+Home, Ctrl+EndFirst cell of the first row, last cell of the last row
PageUp, PageDownMove up or down by one screen
SpaceToggle the focused row
Shift+arrow, Home, End, PageUp/DownMove and select the range from the starting row to the new row (multiple only)
Ctrl+ASelect all visible rows (multiple only)
Ctrl+arrowMove focus and leave the selection alone

The grid ignores keys while an IME is composing text, such as Korean or Japanese input. It also ignores keys pressed inside an input, textarea or select.

Read and change the selection in code ​

ts
api.getSelectedKeys(); // [3, 7]: in selection order, hidden rows included
api.setSelectedKeys([3, 7]); // replace the whole selection
api.clearSelection();

api.focusCell(3, 'name'); // row key and column id
api.scrollToRow(3); // scrolls the least needed if the row is visible

A delete button for the selected rows:

ts
deleteButton.addEventListener('click', () => {
  api.removeRows(api.getSelectedKeys());
});

selectionChanged fires once, and only when the selection actually changes. Setting the same keys again fires nothing.

ts
api.on('selectionChanged', ({ selectedKeys }) => {
  deleteButton.disabled = selectedKeys.length === 0;
});
api.on('focusChanged', ({ rowKey, columnId }) => console.log(rowKey, columnId));

Select by key or value, and select all scopes ​

These are friendlier than setSelectedKeys. All follow the same selection rules (locked rows, the single-selection limit, unknown keys), and each call fires selectionChanged once, only when something changed.

MethodWhat it does
selectRows(keys, { add })Select the given keys. With add: true they are added to the selection, otherwise they replace it. Unknown keys, locked rows, or more than one key in single mode fail with invalid-option and leave the state unchanged
deselectRows(keys)Deselect those keys
selectWhere(match, { add })Select the rows matching the same condition as findRows (an object or a function). Locked rows are skipped silently, and the number selected is returned
getSelectedRows()The selected rows in data order
isSelected(key)Whether that row is selected
selectAllRows({ scope })Select all. Only in multiple mode
deselectAllRows()Clear the selection
selectAllCells(), selectColumnCells(id, { add })Select all cells, or all cells of one column, as one range. selectColumnCells needs cellSelection: 'multiple'

The scope of selectAllRows is 'visible' (default, the same set as the header checkbox), 'page' (the current page), 'filtered' (all pages passing the filter) or 'all' (every row). Locked rows are left out in every scope, and the rows are added to the existing selection.

ts
api.selectRows([1, 4, 7]);
api.selectWhere({ team: 'Dev' }, { add: true });
api.selectAllRows({ scope: 'filtered' });

A range returned by getCellRanges() gets reversed: true only when it was dragged against the reading order (top to bottom, left to right). It is ignored on input.

See the gallery examples Select rows by key or value from code and Select all scopes and cell selection.

Click modes and focus options ​

Without them everything behaves as today. Pass selection as an object and add the following.

OptionDefaultDescription
selection.clickTogglefalseWith true, a plain click on an already selected row deselects that row
selection.checkboxOnlyfalseWith true, clicking the row body does not select (focus still moves); only the checkbox and the keyboard Space do
selection.canDeselecttrueWith false, Ctrl+click, the checkbox, clickToggle, Space and the header checkbox cannot clear a selection. Code (deselectRows, clearSelection, ...) still can
focusabletrueWith false, clicking does not set cell focus, no focus mark is drawn, and arrow, Tab, Home/End and Space navigation is not handled (Ctrl+A still works). Keyboard users cannot tell which cell they are on, so check accessibility. focusCell keeps working
textSelectablebrowser defaultWith true, body text can be dragged and selected with the mouse, and a click right after dragging text is not treated as a row selection (a plain click still selects). Cell drag selection rests then; extend ranges with Shift+click or the keyboard. With false, body text selection is blocked
cellMultiRangetrueWith false, a new cell range always replaces the old one (Ctrl+drag and add of selectCells included)
ts
selection: { mode: 'multiple', checkbox: true, checkboxOnly: true, canDeselect: false },
cellSelection: 'multiple',
cellMultiRange: false,

Try them one at a time in the gallery example Change how clicks select rows.

Make rows unselectable ​

Since 1.2.0

isRowSelectable is available since 1.2.0. It is not available in 1.1.0.

The samples below assume the columns and rows you built earlier and the api the grid returned.

Lock rows that must not be picked, such as paid orders, with isRowSelectable. A row is locked when it returns false.

ts
const isLocked = (row) => row.status === 'Paid';

const options = {
  columns,
  rows,
  rowKey: 'id',
  selection: { mode: 'multiple', checkbox: true },
  isRowSelectable: (row) => !isLocked(row),
};

// In code, pass only keys of rows that can be selected
api.setSelectedKeys(
  api
    .getRows()
    .filter((row) => !isLocked(row))
    .map((row) => row.id),
);
  • Locked rows cannot be picked by click, checkbox or Space. Shift ranges, Ctrl+A and the header checkbox skip the locked rows and pick the rest.
  • If setSelectedKeys gets even one locked key, it throws invalid-option and the selection stays as it was. clearSelection() always works.
  • If data or options change so that a selected row becomes locked, the row leaves the selection and selectionChanged fires once.
  • If the callback throws, the row is treated as locked. The grid keeps working and reports it through the error event (code: 'callback-error', where: 'isRowSelectable').
  • A value that is not a function raises invalid-option.
  • A group checkbox skips locked descendants. A group that contains a locked descendant still shows "some selected" even when everything else in it is selected.
  • The theme shows locked rows with muted text and a not-allowed cursor, and the row gets aria-disabled="true" and the class mxg-row-locked. You do not need to dim them yourself (extra opacity would lower the text contrast).

See the gallery example row-selectable.

Block selection with a hook ​

Since 1.3.4

hooks.canSelect is available from 1.3.4.

Where isRowSelectable decides from the row data alone, hooks.canSelect also sees the kind and position of the selection.

ts
hooks: {
  canSelect: ({ kind, rowKey, columnId }) => !(kind === 'cell' && columnId === 'id'),
}
  • For row selection both isRowSelectable and the hook must allow the row. Blocked rows are also left out of select-all and range selection.
  • For cell selection a range asks only its two corner cells, not the cells in between. If either returns false the selection does not change.
  • If the hook throws, the selection is allowed and an error event is emitted.

Row number, checkbox and state columns ​

Three utility columns can sit at the start: the row number (rowNumber), the selection checkbox (check) and the row state (state) (1.3.6). They are not data columns, so they are left out of getColumnState, exports and keyboard movement.

ts
createGrid(el, {
  columns,
  rows,
  rowKey: 'id',
  selection: { mode: 'multiple', checkbox: true },
  extraColumns: ['state', 'rowNumber', 'check'], // visible order
  rowNumbers: { title: 'No.', width: 60, reverse: false, start: 1 },
  stateColumn: { restore: true, width: 44, labels: { failed: 'Not saved' } },
  isRowCheckVisible: (row) => !row.locked,
});
OptionMeaningDefault
extraColumnsThe order of the visible utility columns. When given, showRowNumbers and selection.checkbox no longer decide visibilityRow number, then checkbox, from showRowNumbers and selection.checkbox
rowNumberstitle (header text), width (32-120), start (first number), reverse (count down from the total)#, 48, 1, false
stateColumntrue or { labels, restore, width (24-120) }. Adds the state column at the end of the listnone
isRowCheckVisible(row, rowKey)Returning false draws no checkbox for that row (the cell stays)all shown
  • If extraColumns disagrees with showRowNumbers: true or selection.checkbox: true (turned on but missing from the list) it is an invalid-option error. 'handle' (the drag handle column) works when rowDrag is on and is an invalid-option otherwise (Drag rows to move them).
  • The state cell shows the row's change state (added, modified, removed) and a failed save as an icon with an accessible name. Change the icons with stateAdded, stateModified, stateRemoved and stateFailed in icons. The accessible names have built-in Korean, English, Japanese and Chinese text; override them with labels. It cannot be used with saveMode: 'none' because changes are not tracked.
  • With restore: true the icon is a button that reverts the row with revertRows (restoreRows for a soft-removed row). Rows without changes have an invisible, disabled button.
  • The utility cells of group and summary lines are empty. Pinned columns follow the summed width of the utility columns.
  • The zone of click events is rownum or state (cells) and rownum-header or state-header (headers). columnId is an empty string for them.

At run time change them with setUtilityColumn(name, { visible, width, order }) and read them with getUtilityColumns(). The width of check cannot be changed. The options are resolved again and optionsChanged fires.

ts
api.setUtilityColumn('state', { visible: true, order: 0 });
api.getUtilityColumns(); // [{ id, visible, width, order }, ...]

Handle rows a filter hides ​

A filter does not clear the selection of the rows it hides. getSelectedKeys() therefore includes rows that are not on screen. If you show a count or act only on what the user sees, filter the keys with getVisibleIndexOfKey.

ts
const keys = api.getSelectedKeys();
const shown = keys.filter((key) => api.getVisibleIndexOfKey(key) >= 0);
console.log(`${shown.length} of ${keys.length} selected rows are visible.`);

getVisibleIndexOfKey finds only the rows drawn right now. With paging, a selected row on another page also gives -1, so it is filtered out too. To find only the rows the filter hides, use isRowFilteredOut(key) (from 1.2.0). It is true only for rows the filter removes, and false for a row on another page or for an unknown key.

ts
const hiddenByFilter = keys.filter((key) => api.isRowFilteredOut(key));
const onOtherPages = keys.filter(
  (key) => api.getVisibleIndexOfKey(key) < 0 && !api.isRowFilteredOut(key),
);

Shift range selection, Ctrl+A and the header checkbox act on visible rows only. clearSelection() clears everything, hidden rows included.

Track data changes ​

ChangeSelection
SortUnchanged. A range is computed in the new screen order
removeRowsRemoved keys drop out at once and selectionChanged fires
setRowsOnly keys that exist in the new data stay. A reload from the server keeps the selection
updateRowsUnchanged for the same key
selection mode change'none' clears everything. Going to 'single' keeps only the first row selected

When the focused row disappears or is hidden, focus moves to the row at the same screen position.

Pitfalls ​

  • If one key in setSelectedKeys does not exist, the call throws invalid-option and the selection stays as it was. When you restore keys from a server, check them with getRowByKey first.
  • With selection: 'none', calling a selection method that changes the selection throws invalid-option. So does setting two or more keys in single mode.
  • Tab leaves the grid after the last cell. This is deliberate, so keyboard users never get trapped.
  • rowIndex in rowClicked is a screen line number. Use rowKey for anything that concerns selection.