Cell editing
Set editable: true on a column to edit it. Double-click a cell, or focus it and press Enter. Clear a name or type a negative salary, then press Enter, and validation stops you.
Choose which columns are editable
editable defaults to false. Turn it on only for the columns users may change.
const columns = [
{ id: 'id', title: 'ID' },
{ id: 'name', title: 'Name', editable: true },
{ id: 'salary', title: 'Salary', kind: 'number', editable: true },
// Per row: nobody can edit the bonus of an inactive employee
{ id: 'bonus', title: 'Bonus', kind: 'number', editable: (row) => row.active },
];A column that computes its value with getValue has nowhere to write, so it cannot be editable. Setting editable on it throws invalid-option, and the options are not applied.
Start, confirm and cancel
| Goal | How |
|---|---|
| Start | Double-click a cell, or press F2 or Enter on the focused cell |
| Replace the value | Type a character on the focused cell. Editing starts with that character |
| Confirm | Enter, move to another cell, or click outside |
| Confirm and go on | Tab (Shift+Tab for the previous cell). If the next cell is editable, editing starts there |
| Cancel | Esc |
Where there is no keyboard, such as on a touch screen, you can put an edit start button at the end of a cell (column editButton, see Keyboard use of widgets in cells).
Space does not start an edit. It toggles the row selection (Row selection and keyboard). On a cell that is not editable, none of these keys do anything.
Only one cell is edited at a time. If you start another edit, the current one is confirmed first. If it fails validation, you stay on the current cell.
Use the five built-in editors
When cellEditor is not set, the column kind picks the editor.
kind | Editor | Input element | Confirmed value |
|---|---|---|---|
text (or unset) | text | Text input | String |
number | number | Number input | Number. An empty input is null; non-numbers fail validation |
boolean | checkbox | Checkbox | true or false. Toggle with Space or a click, confirm with Enter |
select | select | Dropdown | The value of the chosen option, in its original type |
date | date | Date input | The same kind of value it was given (Date, YYYY-MM-DD or epoch). Empty is null |
A select column needs editorOptions. Without it, applying the options throws invalid-option.
{
id: 'department',
title: 'Department',
kind: 'select',
editable: true,
editorOptions: [{ value: 'Engineering' }, { value: 'Design' }, { value: 'Product' }],
}For per-row options or editors see Per-row options and editors.
custom columns have no built-in editor. Give them a cellEditor of your own to make them editable. Without one, a double-click does nothing and startEdit throws invalid-option. The value your editor returns goes into the row as is, and required and custom validation still apply.
Edit dates
A kind: 'date' column opens the date editor. Type 2026-03-05, 2026.3.5, 2026/03/05 or 20260305, or open the calendar with the ▾ button on the right. Confirm with Enter.
- Dates are local calendar dates. There is no time zone conversion; the time is local midnight.
- The committed value keeps the kind it was given: a
Datestays aDate, a'2026-05-05'string stays a string and epoch milliseconds stay a number. - A date that does not exist (such as February 30) or a wrong format is not committed and shows an error. Clearing the input gives
null(refused whenrequired). - Put a minimum or maximum date in
validation.custom.
Gallery example: date-editor
Fill and move by dragging
Since 1.4.0
The fill handle (cellFill, fillRange, Ctrl+D and Ctrl+R) and cell range dragging (cellDrag) are available since 1.4.0.
Both write values through the same path as editing (editable, locked, validation, beforeEdit) and make one undo step. Cells that could not be written come back in rejected with a reason. See Fill handle and Drag a cell range.
Edit several lines, colors and weeks
Since 1.5.0
cellEditor: 'textarea' (several lines), cellEditor: 'color' (colors) and kind: 'week' (ISO weeks) are available since 1.5.0. Options and keys are in Multi-line, color and week editors.
Edit months
Since 1.4.0
kind: 'month', the month picker (createMonthPicker) and the month filter cell are available since 1.4.0.
A kind: 'month' column opens twelve month buttons directly, with no day grid. The value is a string without a time zone, YYYY-MM (for example 2026-11). Sorting, filtering and export use this string.
{ id: 'billMonth', title: 'Bill month', kind: 'month', editable: true, dateTime: { min: '2026-01', max: '2026-12' } }| Item | Behavior |
|---|---|
| What opens | Twelve month buttons and a year header. The header opens the year list (12 years per page); picking a year returns to the month panel |
| Pick a month | The month button commits YYYY-MM and closes the picker |
← → | One month (→ in December goes to January of the next year) |
↑ ↓ | Three months |
PageUp PageDown | One year |
Home End | January, December of that year |
Enter | Commit the pointed month |
Esc | Closes the year list if it is open; otherwise closes the picker |
| Typing | 2026-11, 2026.11, 2026/11 and 202611 are accepted. A wrong text shows the reason and keeps the old value |
dateTime.min, max | YYYY-MM. Months outside the range cannot be picked (aria-disabled) |
format.date.stored | Only the tokens YYYY and MM (YYYY.MM, YYYYMM). Any other token is an invalid-option |
| Month names, year text | Follow the language (Korean 2026년, English 2026). dateTime.labels can change them |
- Paste and CSV, JSON and XML import read the same forms; text that cannot be read is rejected.
- The filter cell accepts
2026-03(that month),>=2026-06and2026-01..2026-06. The conditions tab of the filter popup uses the same picker. - Export: CSV, JSON, XML and PDF write the
YYYY-MMstring. xlsx writes a date cell on the first day of that month with the formatyyyy-mm. - Outside a grid, use
createMonthPicker(el, { value: '2026-11', min, max, onChange })from the picker module.getValue()returnsYYYY-MMornull.
Edit times and date-times
Since 1.2.0
kind: 'time', kind: 'datetime', the column dateTime option, the pickers in filter cells, the small-screen sheet and the standalone picker module are available since 1.2.0. They are not available in 1.1.0.
In the samples of this section, api is the value the grid returned.
A kind: 'time' column opens hour and minute lists. A kind: 'datetime' column opens a calendar and the lists together. The editor follows kind, so you do not pick one.
const options = {
columns: [
{ id: 'name', title: 'Name' },
{
id: 'start',
title: 'Start',
kind: 'time',
editable: true,
dateTime: { min: '09:00', max: '18:00', step: 15 },
},
{
id: 'at',
title: 'Event',
kind: 'datetime',
editable: true,
dateTime: {
step: 5,
hour12: false,
isTimeDisabled: (time) => time >= '12:00' && time < '13:00', // lunch cannot be picked
},
},
],
rows: [{ id: 1, name: 'Seoyeon', start: '09:00', at: '2026-11-10 10:00' }],
rowKey: 'id',
};Stored values
A value is a local string with no time zone. Sorting, filtering and export use that string.
kind | Value format | Example |
|---|---|---|
date | YYYY-MM-DD | 2026-11-10 |
time | HH:mm | 14:30 |
datetime | YYYY-MM-DD HH:mm | 2026-11-10 14:30 |
- Times are always stored in 24-hour form. Even when the screen shows AM/PM,
15:30is stored as15:30. - There is no time zone conversion.
2026-11-10 14:30picked in Seoul is still2026-11-10 14:30when opened in Los Angeles. A time that does not exist because of daylight saving (2026-03-08 02:30) is kept as typed. - Input with a
T(2026-11-10T14:30) is accepted but stored with a space. ADateobject or epoch value is read as local time and shown; editing replaces it with a string. - Add
dateTime: { seconds: true }when you need seconds (HH:mm:ss).
dateTime options
| Option | Meaning |
|---|---|
min, max | First and last pickable value (inclusive), written in the column's format |
step | Minute step. A divisor of 60 (5, 10, 15, 30 …). Input off the step is refused |
seconds | Adds a seconds list and seconds in the value |
hour12 | true shows an AM/PM column. When omitted it follows the language |
weekStart, weekNumbers | First day of the week in the calendar (0 Sunday to 6) and week numbers |
isDateDisabled(date) | Receives YYYY-MM-DD; return true to block that day |
isTimeDisabled(time) | Receives HH:mm; return true to block that time |
A wrong option is reported as an invalid-option error when the grid is created (and in setColumns). For example step: 7 is refused because the step must be a divisor of 60. Typing a blocked value does not commit and shows the reason.
Picker behavior and text options
In addition to the options above, a column's dateTime accepts the options in the table below. With none of them set, behavior is the same as before.
| Option | Value | Effect |
|---|---|---|
openOnEdit | true | Open the picker as soon as editing starts; focus stays in the input |
pickOnly | true | Read-only input, value set only through the picker; clicking the input opens it and Backspace/Delete clear the value |
startDate | 'YYYY-MM-DD' or ({ row, rowKey, columnId }) => string | The day the calendar shows first when there is no value; the month of an existing value comes first |
confirm | true | An OK button for the date picker too; a day only highlights until OK or Enter confirms |
placeholder | string | Input hint; wins over the locale hint and editorParams.placeholder |
hourStep | integer 1-12 | Hour step (24-hour hours counted from 0). Other hours leave the list and are refused by validation when typed. The 12-hour list shows a value when either its AM or PM hour fits |
secondStep | 1, 2, 5, 10, 15, 20, 30 | Second step (the minute step is step). Other seconds leave the list and are refused by validation when typed |
allowedHours, allowedMinutes, allowedSeconds | integer arrays (0-23, 0-59) | Selectable hours, minutes and seconds; the rest are dimmed in the lists and refused by validation when typed. They must pass together with isTimeDisabled, min and max. An empty array is an invalid-option |
labels | table below | Replace the calendar heading and month panel text |
The keys of labels. If a callback throws or returns a non-string, it is reported through the error event (callback-error) and the default text is used.
| Key | Value | Replaces |
|---|---|---|
months | 12 strings (from January) | The month buttons of the month panel |
weekdays | 7 strings (from Sunday, independent of weekStart) | The weekday heads of the day grid |
monthTitle | (year, month) => string | The month title above the day panel |
yearTitle | (year) => string | The year title above the month panel |
- With only
months, the month name inside the month title changes too (the year and the order follow the language). AddmonthTitleto change the order or shape. Any other key inlabelsis aninvalid-option. The accessible name (the spoken full date) is not changed. - Typed-value validation (
min,max,step,allowed*,hourStep,secondStep) only applies to columns that havekind: 'date' | 'time' | 'datetime'. A column that only setscellEditorgets the restricted picker lists but no typed-value check. - A malformed value (
startDate: '2026-2-3',hourStep: 0, aweekdayslist that is not 7 long) is aninvalid-optionwhen the grid is created. - The standalone pickers (
createDatePickerand the others) acceptconfirm,startDate(string only),hourStep,secondStep,allowed*andlabels.openOnEdit,pickOnlyand a functionstartDateare for cell editors only and raiseinvalid-optionthere.
Gallery example: edit-date-open
Gallery example: edit-time-steps
Gallery example: edit-date-labels
Keyboard
You can type into the input, or open the picker with ↓ or the icon on the right.
| Key | Action |
|---|---|
↓ (when closed) | Open the picker |
| Arrow keys | Day or week in the calendar; in the time lists up/down changes a value and left/right switches hour/minute |
PageUp / PageDown | One month back or forward. With Shift, one year |
Home / End | Start and end of the week |
Tab | Move between the calendar and the time lists |
Enter | Confirm. In datetime, Enter on a date moves to the time lists |
Esc | Closes only the picker. Press again to cancel the edit |
Pressing Enter on a blocked day does nothing.
Clear with Delete or Backspace
When no cell is being edited, Delete or Backspace on a cell of a date, time or date-time column clears the value to null and the cell goes blank. In 1.1.0 these keys did nothing.
- If a cell range is selected (
cellSelection), every date and time cell in the range is cleared together. Read-only cells (editable: false) and cells of other kinds such as text or number are left alone, and a cell that several overlapping ranges cover is cleared only once. - The write goes through the same path as an edit, so it is tracked as a change and undo (Ctrl+Z) is one step, however many cells were cleared.
- A cell that does not accept an empty value (
validation: { required: true }) keeps its value. When you clear it with the key, the cell is marked as rejected (a border and a "!", plusaria-invalid). The reason is in the cell'stitleand is announced politely to screen readers. ThevalidationFailedevent arrives too (itsmessageis "This field is required." in English). Only user actions mark the cell; when your app callspasteCells, nothing is marked. If a range contains such cells, only those are skipped and the rest are cleared. - While a cell is being edited, the key only deletes text inside the input. Press Enter with an empty input and
nullis saved the same way; for a required cell the reason appears under the input and the editor stays open.
api.on('validationFailed', ({ rowKey, columnId, message }) => {
console.log(`row ${rowKey}, ${columnId}: ${message}`); // when a key tried to clear a required cell
});Use it in the filter
With filterRow: true, the filter cells of date, time, datetime and month columns get a calendar or clock button. Type the value or pick it with the button; the same filter is applied. A picked value is written into the cell, and the filter applies when you press Enter.
| What you write | Meaning |
|---|---|
2026-11-10 | That whole day (also in datetime, whatever the time) |
>=2026-11-11, <=11:00 | From then on (inclusive), up to then (inclusive). > and < leave that value out |
2026-11-10 10:00..2026-11-11 16:05 | A range, both ends included. For times write 09:00..12:00 |
A wrong format turns the cell red and that condition is not applied. You can apply the same filter from code; it builds the same model as typing.
api.setFilterModel({
match: 'all',
items: [{ columnId: 'at', operator: 'between', value: ['2026-11-10 10:00', '2026-11-11 16:05'] }],
});
api.setFilterModel(null); // clearThe filter follows only step, seconds, hour12, weekStart and weekNumbers of the column's dateTime. min, max, isDateDisabled and isTimeDisabled are not applied to filters, so they never limit what you can search for.
Use it on a small screen
When the screen is 520px wide or less, the picker opens as a sheet that rises from the bottom instead of a popup under the cell. A dark backdrop covers the page behind it; tapping the backdrop closes the sheet and cancels the edit. On touch the items are 44px high and the input text is 16px, so iOS does not zoom the page. There is no option to switch on.
Use it without a grid
The same pickers work outside a grid. The optional module maxgrid.picker.min.js loads after maxgrid.min.js and adds createDatePicker, createTimePicker, createDateTimePicker and createMonthPicker (1.4.0) to MaxGrid.picker.
<div id="due"></div>
<script src="https://cdn.maxmine.com/maxgrid/1.8.0/maxgrid.min.js"></script>
<script src="https://cdn.maxmine.com/maxgrid/1.8.0/maxgrid.picker.min.js"></script>
<script>
const picker = MaxGrid.picker.createDatePicker(document.getElementById('due'), {
value: '2026-11-10',
min: '2026-01-01',
weekStart: 1,
locale: 'en',
onChange: (value) => console.log(value), // '2026-11-12'. null when cleared
});
picker.setValue('2026-12-25'); // does not call onChange
picker.getValue(); // '2026-12-25'
picker.destroy(); // removes the DOM and every listener
</script>- The options are the column's
dateTimeoptions (min,max,step,seconds,hour12,weekStart,weekNumbers,isDateDisabled,isTimeDisabled) plusvalue,locale,localePacks,onChangeandariaLabel. The value formats are the same (YYYY-MM-DD,HH:mm,YYYY-MM-DD HH:mm). onChangefires when a day is picked for dates, on every change for times, and on OK or Enter for date-times.- A wrong option (for example
step: 7) throwsinvalid-optionwhen you create the picker. - In npm, use
import { createDatePicker, createTimePicker, createDateTimePicker } from 'maxgrid/picker'(from 1.2.0). Installingmaxgridalone is enough: this entry is a self-contained module, so no other package is needed, and the types come with it. The script-tag file ismaxgrid.picker.min.js(globalMaxGrid.picker; that file has no types).
Gallery example: edit-time-picker
Gallery example: edit-datetime-picker
Gallery example: edit-date-limits
Gallery example: filter-datetime-picker
Gallery example: filter-datetime-range
Edit a whole row
To fix several cells of a row and commit them together instead of one cell at a time, set editMode: 'row'.
createGrid(el, {
editMode: 'row',
rowValidator: (row) => (row.end < row.start ? { end: 'End must not be before start.' } : null),
// ...
});| To do this | Do this |
|---|---|
| Next cell in a row | Tab (Shift+Tab for the previous). Each cell is written at once and shows on screen |
| Commit the row | Enter on the last cell, Tab out of the row, click another row, or stopEdit() |
| Cancel the row | Esc or stopEdit({ cancel: true }). Every cell edited in the row goes back |
- Committing a row runs
rowValidator(row). A string lands on the first changed cell;{ columnId: message }lands on those cells and the problem cell opens again.validationFailedis emitted too. - Row editing emits
rowEditStarted { rowKey }(since 1.3.4),rowEditCommitted { rowKey, cells }androwEditCancelled { rowKey, reason }.cellsholds the first and last value of each changed cell. - The row being edited gets the
mxg-row-editingclass. save()commits a row edit in progress first.editMode: 'row'cannot be combined withsaveMode: 'immediate'(invalid-option).
Gallery example: row-edit
Editing pinned rows, pinned columns and group fields
- Cells in pinned rows (
pinnedRows) and pinned columns (pinned) are edited and committed like any other cell. - Committing an edit of the grouping field (a column in
grouping.by) moves the row under its new group (groups are recomputed through the pipeline). Focus stays on the edited cell in its new place and the selection is kept. There is no option to turn on. - Touch: a 400 ms long press on a header or row handle starts a column move or row drag. A short drag scrolls. There is no option for this delay yet.
Using the grid in a modal dialog
When the grid sits in a modal <dialog>, the filter, column and cell menus open inside the grid and stay visible. The date/time picker popup is placed in the document, and it now goes into the nearest open <dialog> so the modal never hides it. To place it somewhere else, pass an element as popupParent (used only while it is attached to the document). Priority: popupParent, an open <dialog>, then document.body.
Undo and redo
Committed edits are recorded automatically. While no cell is being edited, Ctrl+Z (⌘+Z on Mac) undoes and Ctrl+Y or Ctrl+Shift+Z redoes. In code:
api.undo(); // true if something was undone, false if there was nothing to undo
api.redo();
api.canUndo();
api.canRedo();
api.clearHistory();
api.on('historyChanged', ({ canUndo, canRedo }) => {
undoButton.disabled = !canUndo;
redoButton.disabled = !canRedo;
});- One step is one committed edit. With row editing, every cell changed in that row is one step.
- Undo writes the previous value back, so it agrees with change tracking: a value back at its original drops out of the pending changes, and redo brings it back.
- A step whose value has since changed (a rollback, a server update) or whose row is gone is skipped. Replacing all data with
setRowsclears the history. undoLimit(default 100, 0 turns undo off) sets how many steps are kept.- Calling
undo()orredo()cancels a cell that is being edited. - An
updateRowsoraddRowscall from your code is not recorded; only committed edits are. Since 1.2.0,removeRowsandupdateRowsare the exception (next section).
Gallery example: undo-redo-api
Undo row removal and updates
Since 1.2.0
Undoing removeRows and updateRows is available since 1.2.0. In 1.1.0 they are not recorded.
The samples below assume the columns and rows you built earlier and the api the grid returned.
One removeRows or updateRows call from your code is one undo step. It goes into the same history as cell edits (undo, redo, canUndo, historyChanged, undoLimit).
api.removeRows([1, 2]); // one step
api.updateRows(api.getRows().map((row) => ({ ...row, stock: 100 }))); // one step
api.undo(); // undoes the update
api.undo(); // undoes the removal; the rows return to their old positions
api.redo(); // removes them again- Only rows that were really removed or changed are recorded. Passing only unknown keys, or passing rows whose values did not change at all to
updateRows(the objects you already have or{ ...row }copies), creates no step. If even one row changed, the call is one step. Copies with equal values also send norowsChanged; if you change an object in place and pass that same object,rowsChangedis sent but no step is recorded. addRows,transactandsetRowsare not steps.setRowsclears the history.- When a grid feature changes rows internally (a cell edit, a paste, a save result,
mergeRows), it is recorded once. It is not recorded a second time asremoveRowsorupdateRows. - If a removed row's key exists again when you undo, that step is stale and is skipped, and
undo()returnsfalse. A change is skipped too when the row's current value differs from the value the step left. - Selection and focus are not restored. A row that left the selection when it was removed is not selected again by undo.
- With
undoLimit: 0nothing is recorded. - On undo and redo,
historyChangedalso carries the affected row keys (rowKeys) and how many of them the filter hides (hiddenCount). When hidden rows change, nothing looks different on screen, so you can use this value to show a note such as "N rows are hidden by the filter".
See the gallery example row-remove-undo.
Validate input
Add validation to a column, and the grid checks the value when the user confirms. The order is value type, required, min and max and maxLength, then custom. The first rule that fails supplies the message.
{
id: 'salary',
title: 'Salary',
kind: 'number',
editable: true,
validation: {
required: true,
min: 0,
max: 1_000_000,
custom: (value, row) =>
row.department === 'Intern' && Number(value) > 40_000
? 'Intern salary is capped at 40,000.'
: null,
},
}| Rule | Fails when |
|---|---|
required | null, undefined, an empty string, or only whitespace |
min, max | A number outside the range |
maxLength | A longer string |
custom | Returns a string (the message). null passes |
On failure the grid does not write the value and keeps the editor open. The input gets aria-invalid, and the message appears as its title. validationFailed fires. Built-in messages follow the locale option (ko or en). If custom throws, the grid treats it as a failure and fires an error event.
The same rules run again just before a save.
Keep values unique
Set unique: true in a column's rules and its values must be unique across all data rows. Empty values are ignored, strings are compared after trimming, numbers by value, and the cell being edited is left out of its own comparison. The check uses the current data, including unsaved changes, and applies to typing, paste and save().
{ id: 'code', editable: true, validation: { required: true, unique: true } }Validate on demand
api.validateRows() checks the current data against the rules at any time and returns the errors (CellError[]). It emits no validationFailed event and does not move focus or scroll.
const errors = api.validateRows({
changedOnly: true, // only added and modified rows (default: all rows)
columnIds: ['code', 'qty'], // only these columns
keys: [1, 2, 3], // only these rows
check: (row) =>
// append your own row-level check
row.start > row.end
? { rowKey: row.id, columnId: 'end', message: 'Must be after the start.' }
: null,
});- Errors are sorted by visible row order, then column order. Rows that cannot be edited are checked too.
- The
rowValidatoroption is not run; pass row-level checks ascheck. Ifcheckthrows, oneerrorevent (callback-error) is emitted and only that row'scheckis skipped. - For an open editor use
api.validateEditor()(checks it and shows the error in the editor;truewhen no editor is open) andapi.getEditorErrors()(the error of the current input, empty when none). Neither commits the edit.
Set input attributes
To set attributes on the input of the built-in text, number, date and time editors, give the column editorParams. Anything you leave out behaves exactly as before.
{
id: 'phone',
editable: true,
editorParams: {
inputMode: 'tel', // mobile keyboard: none | text | decimal | numeric | tel | search | email | url
maxLength: 13, // limit typed characters (1-10000)
align: 'end', // text alignment: start | center | end
autoComplete: false, // false -> off, true -> on, a string is used as is
placeholder: '010-0000-0000',
},
}- In the number editor
maxLengthlimits the typed characters (commas included), not the value. Limit the value withvalidation.max. - Text is never cut during IME composition; the browser handles
maxlength. - A custom editor receives the same object as
ctx.editorParams. - The checkbox and select editors ignore these attributes.
Relax checks on paste
Paste goes through the same checks as an edit, cell by cell. To keep a column out of paste use pasteable: false; to accept extra lines as new rows use clipboard.addRows (Copy and paste). For a column that takes bulk data from a spreadsheet you can skip the required, range, length and custom rules on paste with pasteCheck: 'type-only'. The value type (number or date format) is still checked, and wrong values count as skipped cells. Typing is not affected. The default is 'full'.
Change values with a checkbox or switch
Use cellRenderer: 'switch', or 'checkbox' with parameters, and pressing the control in the cell changes the value at once. The value goes through the normal edit commit path, so validation, undo and change tracking work as usual. The options are in "Checkbox and switch" of Built-in cell renderers.
Set input rules
Number and text editors take input rules in editorParams. Keys you leave out behave as before. Each editor accepts only its own keys; a key from another editor is an invalid-option.
| Key | Editor | Value | Effect |
|---|---|---|---|
decimals | number, percent | 0-10 | Digits after the point; 0 means integers only |
negative | number, percent | false | Block the - key |
group | number, percent | true or one character | Thousands separator while typing |
scale | number, percent | a number above 0 | Stored value = shown value / scale |
case | text | 'lower', 'upper' | Lower- or upper-case the input |
secret | text | true | Hide the input like a password field |
pattern | text | RegExp source (max 200 chars) | Whole-value match check |
patternMessage | text | message | Shown on a mismatch; when set the input is also checked while typing |
{ id: 'amount', kind: 'number', editable: true,
editorParams: { decimals: 2, negative: false, group: true } },
{ id: 'code', editable: true,
editorParams: { case: 'upper', pattern: '[A-Z]{2}\\d{3}', patternMessage: '2 letters and 3 digits' } },- Number rules block disallowed characters as you type, and pasted text keeps only the characters the rules allow. While an IME composition is active nothing is changed; the text is fixed when the composition ends.
groupkeeps the caret where it was when separators are inserted.trueuses the separator of the gridlocale.- The decimal point is always
.. If the language's thousands character is.(German and others),group: trueuses a comma. Pressing Delete or Backspace next to a separator skips it and deletes the digit. scaleconverts between the shown value and the stored value. Committing without touching the value keeps the original value.patternis checked on commit and by pre-save validation (validateRows). An empty value passes;validation.requiredhandles required fields. WithoutpatternMessagethe default message ("The value is not valid.") is used.- A
patternwith a repetition inside a repetition (such as(a+)+) can freeze commit on some input, so it is rejected withinvalid-option. The length cap is 200 characters. secretonly hides the text. It does not block copying, and the typed value is never put into the accessible name or description.
Percent editor
cellEditor: 'percent' shows a stored 0.25 as 25 and adds % after the input. It allows 2 decimals by default; change that with decimals and scale (default 100). Give the range in stored units, for example validation: { min: 0, max: 1 }. The editor belongs to the optional editors bundle. Without it, using it raises an invalid-option that asks for maxgrid/editors. The integrated bundle (maxgrid.min.js) includes it.
{ id: 'rate', kind: 'number', editable: true, cellEditor: 'percent',
validation: { min: 0, max: 1 } }Mask editor
cellEditor: 'mask' makes people type a value in a fixed shape such as a phone number. The pattern and options are in Mask editor.
Stepper editor
cellEditor: 'stepper' adds increase and decrease buttons to a number cell. Options and keys are in Stepper editor.
Combobox editor
cellEditor: 'combobox' is a pick editor whose list is filtered as you type. Options and keys are in Combobox editor.
Multiselect editor
cellEditor: 'multiselect' picks several items in one cell. Options and values are in Multiselect editor.
Remote search editor
cellEditor: 'remote' fills its list by asking a server as you type. Options and the request flow are in Remote search editor.
Add and remove rows with the keyboard
Since 1.5.0
The keyboardRows option is available since 1.5.0. It is off by default, and without it nothing changes.
keyboardRows: true lets people add and remove rows with the keyboard alone. You can turn on only one side with { insert: true } or { delete: true }.
createGrid(el, {
columns,
rows,
rowKey: 'id',
keyboardRows: true,
hooks: {
beforeRemoveRows: ({ source, keys }) =>
source !== 'keyboard' || confirm(`Remove ${keys.length} rows?`),
},
});| Key | Action |
|---|---|
| Insert, Ctrl(⌘)+Plus | Adds one blank row after the focused row (at the end when nothing is focused) with addRows |
| Ctrl+Delete, ⌘+Backspace on Mac | Removes the selected rows (or the focused row when none) with removeRows |
- New row: the column
defaultValues are filled in. WhenrowKeyis a field name the key is the largest number plus 1 if all keys are numbers, otherwisenew-1,new-2… . WithoutrowKeythe row object is the key. - Focus: when the new row is visible, focus goes to its first editable cell and the edit starts if
singleClickEditis on. A row hidden by sort, filter or paging leaves the focus alone. - Veto and confirm:
beforeAddRowsandbeforeRemoveRowsreceivesource: 'keyboard'(calls from code have'api'). Returningfalsechanges nothing. There is no confirmation dialog of its own. - When it does nothing: while an editor is open, during IME composition, or when
hooks.onKeyDownreturnstrue. - Errors at creation:
insertcannot be on whenrowKeyis a function, and neither side works withrowModel: 'infinite'(invalid-option). - There is no API to set a row state (
added,modified,removed) by hand. UseacceptRows(mark as saved),revertRows(undo) and soft removal (removeMode) for the same needs.
Set the editor box size and position
By default the editor covers the cell and grows downward with its content. Give a column editorBox to set its size and placement. It applies to the built-in text, number, date, time and datetime editors and to editors you write. The date and time picker popups keep their own placement.
{
id: 'memo',
editable: true,
cellEditor: myTextareaEditor,
editorBox: {
side: 'below', // over (default, covers the cell) | below | above
align: 'end', // start (default) | end: align the end edge with the cell's end edge
width: 320, // 20-2000 px or 'cell' (default, grows with content)
height: 120, // same range; larger content scrolls inside the box
minWidth: 240, // lower bound for the size
offsetX: 0, // -500..500 px, shifts the box further
offsetY: 4,
},
}- With an explicit size, overflowing content scrolls inside the box. If there is no room the box flips to the other side, and if that does not fit either it is pushed into the visible area. Offsets are added to the wanted position before this correction runs.
- In right-to-left documents (
dir="rtl"),align: 'end'is the left edge. - Pinned column and pinned row corrections are unchanged. Without
editorBoxthe placement is identical to 1.3.2.
Step in before and after an edit
Since 1.3.4
hooks.beforeEdit, hooks.transformEdit and hooks.beforeUndo are available from 1.3.4.
hooks: {
beforeEdit: ({ rowKey, columnId, trigger }) => !isLocked(rowKey), // false: the editor does not open
transformEdit: ({ columnId, value, oldValue }) =>
columnId === 'code' ? String(value).toUpperCase() : undefined, // undefined keeps the value, null clears it
beforeUndo: () => !saving, // false: nothing is undone
}beforeEditruns when an edit starts by double click, key, single click orstartEdit. WithfalsenoeditStartedis emitted and another open edit stays as it is. Paste and clearing cells do not open an editor and are not asked.transformEditruns when the editor commits and for each pasted cell. It receives the value after the columnemptyAs, and the value you return is validated. If validation fails the editor stays open.validateEditor()and the check while typing judge the value after the same transform.- Starting a row edit (
editMode: 'row') emitsrowEditStarted { rowKey }once. - The general hook rules are in Events.
Turn typed text into a value
Since 1.3.4
The column options parse, format.date.stored and dateTime.clearValue are available from 1.3.4.
- The column
parse(raw, row)turns typed text into a value. Withparseset, the default number editor also hands over the raw text instead of converting it to a number. If it throws or returnsundefinedthe edit is not committed and the editor stays open. - The commit order is
beforeEdit-> editor ->parse->hooks.transformEdit-> validation -> store. - For a column with
format.date.stored, the editor and validation see the standard date value and only the write converts to the stored shape.oldValueandnewValueofeditCommittedare standard values too. - With
dateTime.clearValueset, the calendar's Clear (committing a blank) writes that value. A non-empty text skips date validation. Without it a blank staysnullas today. - See Columns for the formats.
Choose key navigation while editing
The default key behavior stays as it is; change only what you need with editNav. With nothing set, behavior is identical to 1.3.2.
createGrid(el, {
columns,
rows,
editNav: {
enter: 'down', // after Enter commits: stay (default) | down | up | right
tabStartsEdit: false, // Tab only moves focus to the next cell, no edit starts (default true)
skipReadonly: true, // arrows, Home/End and Tab skip columns that cannot be edited
arrowCommit: true, // while editing, Up/Down commit and move (text, number, date, time editors)
backspaceStarts: true, // Backspace/Delete start editing a text or number cell with an empty value
},
singleClickEdit: 'all', // one click starts any editor (true: checkbox and select only, false: off)
});enter: at the edge (last row or column) it only commits and stays. In row edit mode (editMode: 'row') it moves after the row is committed.skipReadonly: nothing is skipped when no column can be edited. A per-roweditablefunction counts as editable.arrowCommit: Left/Right stay in the input. Editors such as the select keep Up/Down for themselves. Nothing happens during IME composition.backspaceStarts: does not start when more than one cell is selected. Delete on date and time cells still clears the value.
Two more options per column:
{ id: 'memo', navigable: false } // keyboard movement and Tab skip this column (the mouse still focuses it)
{ id: 'code', suppressKey: ({ event, editing }) => event.key === 'Enter' && !editing }When suppressKey returns true the grid does nothing for that key (and does not prevent the browser default). It is called while editing too. If it throws, the key is not suppressed and an error event (callback-error) is emitted.
Type Korean text
While a Korean syllable is being composed, the characters are not final. If the user presses Enter, or the input loses focus, in the middle of composition, the grid does not confirm. It retries once right after composition ends, so the last character is never lost.
If the first key that starts an edit is a Korean key, editing starts with an empty input and the input takes over the composition. How smoothly the first character carries over differs by browser, so test in Chrome, Edge and Safari if your users type Korean.
An editor you write yourself must report whether it is composing (isComposing). How to write one is in Write a cell adapter.
Start and stop an edit in code
api.startEdit(3, 'name'); // row key, column id
api.stopEdit(); // confirm
api.stopEdit({ cancel: true }); // cancelstartEdit needs a visible row (a row hidden by a filter fails), and a visible, editable column. If any condition fails it throws invalid-option. When a user starts an edit with a double-click or a key under the same conditions, the grid ignores it without an error.
Read the edit state
| Method | Returns |
|---|---|
isEditing() | Whether an edit is in progress |
getEditing() | { rowKey, columnId, trigger } or null. In row edit mode (editMode: 'row') columnId is null |
getEditValues() | The values being edited, { [columnId]: value }, or null |
getHistoryInfo() | { undoCount, redoCount, limit } |
In cell edit the open editor's uncommitted value is included (when a renderer draws the editor). In row edit mode it is the cells committed so far in that row plus the open editor's value. Without the editing bundle these methods throw the error that names the bundle.
Listen to edit events
api.on('editCommitted', ({ rowKey, columnId, oldValue, newValue }) => {
console.log(`Row ${rowKey}, ${columnId}: ${oldValue} → ${newValue}`);
});| Event | Payload | Fires |
|---|---|---|
editStarted | { rowKey, columnId, trigger, startKey? } | When editing starts |
editCommitted | { rowKey, columnId, oldValue, newValue } | When a changed value is confirmed |
editCancelled | { rowKey, columnId, reason } | When the editor closes without writing |
validationFailed | { rowKey, columnId, value, message } | When validation fails and the editor stays |
editRequested | { rowKey, columnId, value, oldValue, apply, reject } | Instead of committing when editApply is 'app' |
editRejected | { rowKey, columnId, value, message } | When the app calls reject() |
Every edit ends with exactly one of editCommitted and editCancelled. reason is user (Esc), api, unchanged (same value), rowRemoved, columnChanged or destroyed.
Let the app apply edits
For values a server must confirm first, set editApply: 'app' so the app writes instead of the grid. The default 'grid' writes immediately as before.
createGrid(el, { columns, rows, editApply: 'app' });
api.on('editRequested', async ({ rowKey, columnId, value, apply, reject }) => {
const res = await fetch(`/api/rows/${rowKey}`, {
method: 'PATCH',
body: JSON.stringify({ [columnId]: value }),
});
if (res.ok) apply();
else reject('The server did not accept the value');
});- When an editor commits (typing, picker, select, checkbox toggle), the value is parsed, transformed and validated, then handed to
editRequestedinstead of being written. The editor closes (aneditCancelledwith reasonapifires first) and the cell gets themxg-cell-pendingclass. apply()writes the value then, like a normal edit: one undo step andeditCommitted.reject(message)emitseditRejectedand shows the same rejected mark as a failed validation. The value is unchanged.- Only the first call counts. Calls after the row was removed or the grid was destroyed are ignored.
- A pending cell cannot be edited again.
updateCells,fillColumn,pasteCells,setRowsand row edit mode (editMode: 'row') are not affected byeditApply.
Undo many writes as one
Every write between beginBulkEdit() and endBulkEdit() (editor commits, paste, updateCells, fillColumn) becomes one undo step. Change events still fire per write.
api.beginBulkEdit();
api.fillColumn('status', 'checked');
api.updateCells([1, 2], { owner: 'me' });
api.endBulkEdit(); // one Ctrl+Z reverts everything
// api.endBulkEdit({ commit: false }) cancels all writes in the groupendBulkEdit({ commit: false })reverts the group at once and leaves nothing in undo or redo.- Calling
beginBulkEdit()while open, orendBulkEdit()while not open, throwsinvalid-option. - Events
bulkEditStartedandbulkEditEnded { count, committed }fire. Destroying the grid during a bulk closes it without events. - With
undoLimit: 0there is no history, socommit: falsecannot cancel.
Expect these changes while editing
- Changing the sort or filter leaves the edited row at its starting screen position, and the typed value stays. The row finds its place after the edit ends.
updateRowson the same key keeps the edit going. On confirm, the grid writes to the latest version of the row.removeRowsorsetRowsthat drops the row cancels the edit withrowRemoved.- A column that disappears, or loses
editable, cancels the edit withcolumnChanged. - Moving the selection or focus to another cell confirms the edit.
Pitfalls
- Confirming without changing the value fires
editCancelledwithreason: 'unchanged', noteditCommitted. Detect changes witheditCommitted. - If the confirmed value is a sort key, the row moves to a new position. Focus follows the row key.
- Editing works with
saveMode: 'none'. Only change tracking is off (Save changes in a batch). - Tab passes through read-only cells. It does not skip ahead to the next editable cell.
- The grid writes values with
textContentandvalueonly, so HTML a user types shows as plain text.