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.
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.
const options = {
columns,
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};| Mode | Behavior |
|---|---|
'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
| Action | Result |
|---|---|
| Click a row | Selects only that row |
| Ctrl+click (Cmd on Mac) | Toggles that row |
| Shift+click | Selects the range from the last selected row to the clicked row |
| Click a checkbox | Toggles that row. No Ctrl needed |
| Shift+click a checkbox | Adds 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.
- 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.
- The range grows towards the finger. At an edge the grid scrolls and the range keeps growing.
- Lift the finger to finish. The range stays, so you can copy it, make a chart from it or fill it.
- 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
cellLongPressedand 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.
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.
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
},
});| Item | Content |
|---|---|
| Start | Press inside the range and drag (mouse 4px, touch 400ms) |
| Outside, Shift | Range selection |
| Drop position | Cell 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 table | Cancelled (invalid-target) |
| Edges | Auto-scroll |
| Cancel | Esc, losing window focus, pointer cancel |
| Writing | Same checks as editing, one undo step |
| Cells not written | Reported in rejected with a reason |
| After the drop | Selection = 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 inrejectedwith a reason.Touch: while you long-press, neither the cell menu nor the browser menu opens.
rejectedincellsDroppedis a list of{ rowKey, columnId, reason }.reasonis a word such asnot-draggable,merge,not-data, or a validation message.countincellsDroppedis 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
rowDragin 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.
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)
);| Item | Content |
|---|---|
| When the handle shows | One selected range + a fillable column (end corner cell) |
| Direction | The axis moved more ('x', 'y' lock it) |
| Default rule | Repeat; a series for two or more numbers with a constant step |
| Decimals | Rounded to 10 places (editorParams.decimals first) |
| Shrinking | Clears the cells that leave (kept with clearOnShrink: false) |
fill callback | Returns the values of the part outside the source |
| Ctrl+D, Ctrl+R | Fill the first row or column over the whole range |
| Writing | Same checks as editing, one undo step |
| Cells not filled | Reported in rejected with a reason |
| Cancel | Esc, 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.fillcallback: 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 anerrorevent.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
fillRangetarget must contain the source and extend it along one axis only; otherwise it is aninvalid-optionbefore any state changes. Extending up or left continues the series backwards.opts.directionmust match the target.The event
fillEndedcarries{ source, target, direction, count, rejected }. If the hookbeforeFill({ sourceRange, targetRange, direction })returnsfalse, 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.
| Key | Action |
|---|---|
| ← ↑ → ↓ | Move one cell. Stops at the edge |
| Tab, Shift+Tab | Next or previous cell. At a row end, wraps to the next or previous row. Past the last cell, focus leaves the grid |
| Home, End | First or last column of the current row |
| Ctrl+Home, Ctrl+End | First cell of the first row, last cell of the last row |
| PageUp, PageDown | Move up or down by one screen |
| Space | Toggle the focused row |
| Shift+arrow, Home, End, PageUp/Down | Move and select the range from the starting row to the new row (multiple only) |
| Ctrl+A | Select all visible rows (multiple only) |
| Ctrl+arrow | Move 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
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 visibleA delete button for the selected rows:
deleteButton.addEventListener('click', () => {
api.removeRows(api.getSelectedKeys());
});selectionChanged fires once, and only when the selection actually changes. Setting the same keys again fires nothing.
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.
| Method | What 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.
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.
| Option | Default | Description |
|---|---|---|
selection.clickToggle | false | With true, a plain click on an already selected row deselects that row |
selection.checkboxOnly | false | With true, clicking the row body does not select (focus still moves); only the checkbox and the keyboard Space do |
selection.canDeselect | true | With false, Ctrl+click, the checkbox, clickToggle, Space and the header checkbox cannot clear a selection. Code (deselectRows, clearSelection, ...) still can |
focusable | true | With 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 |
textSelectable | browser default | With 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 |
cellMultiRange | true | With false, a new cell range always replaces the old one (Ctrl+drag and add of selectCells included) |
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.
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
setSelectedKeysgets even one locked key, it throwsinvalid-optionand 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
selectionChangedfires once. - If the callback throws, the row is treated as locked. The grid keeps working and reports it through the
errorevent (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-allowedcursor, and the row getsaria-disabled="true"and the classmxg-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.
hooks: {
canSelect: ({ kind, rowKey, columnId }) => !(kind === 'cell' && columnId === 'id'),
}- For row selection both
isRowSelectableand 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
falsethe selection does not change. - If the hook throws, the selection is allowed and an
errorevent 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.
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,
});| Option | Meaning | Default |
|---|---|---|
extraColumns | The order of the visible utility columns. When given, showRowNumbers and selection.checkbox no longer decide visibility | Row number, then checkbox, from showRowNumbers and selection.checkbox |
rowNumbers | title (header text), width (32-120), start (first number), reverse (count down from the total) | #, 48, 1, false |
stateColumn | true or { labels, restore, width (24-120) }. Adds the state column at the end of the list | none |
isRowCheckVisible(row, rowKey) | Returning false draws no checkbox for that row (the cell stays) | all shown |
- If
extraColumnsdisagrees withshowRowNumbers: trueorselection.checkbox: true(turned on but missing from the list) it is aninvalid-optionerror.'handle'(the drag handle column) works whenrowDragis on and is aninvalid-optionotherwise (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,stateRemovedandstateFailedinicons. The accessible names have built-in Korean, English, Japanese and Chinese text; override them withlabels. It cannot be used withsaveMode: 'none'because changes are not tracked. - With
restore: truethe icon is a button that reverts the row withrevertRows(restoreRowsfor 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
zoneof click events isrownumorstate(cells) andrownum-headerorstate-header(headers).columnIdis 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.
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.
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.
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
| Change | Selection |
|---|---|
| Sort | Unchanged. A range is computed in the new screen order |
removeRows | Removed keys drop out at once and selectionChanged fires |
setRows | Only keys that exist in the new data stay. A reload from the server keeps the selection |
updateRows | Unchanged 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
setSelectedKeysdoes not exist, the call throwsinvalid-optionand the selection stays as it was. When you restore keys from a server, check them withgetRowByKeyfirst. - With
selection: 'none', calling a selection method that changes the selection throwsinvalid-option. So does setting two or more keys insinglemode. - Tab leaves the grid after the last cell. This is deliberate, so keyboard users never get trapped.
rowIndexinrowClickedis a screen line number. UserowKeyfor anything that concerns selection.