FreeGridv1.15.1한국어

Editing

Edit cells in place with calendars, date ranges, combo, multi-select, radio, switch, number, phone-number mask and dialog editors, per-cell editable rules, row editing and cancellable changes.

Live demoEditing

Edit cells in place with text, number, date and select editors, validation, undo and change tracking.

Code for this demo
import { createGrid, type ColumnDef, type Row } from '@freegridjs/core';
import { makeRows } from '../data';
import { button, separator, text, tr, type DemoContext } from '../ui';

const CITIES: Record<string, string[]> = {
  'South Korea': ['Seoul', 'Busan', 'Incheon'],
  Japan: ['Tokyo', 'Osaka', 'Kyoto'],
  Germany: ['Berlin', 'Munich', 'Hamburg'],
  France: ['Paris', 'Lyon', 'Marseille'],
  Spain: ['Madrid', 'Barcelona', 'Valencia'],
  China: ['Beijing', 'Shanghai', 'Shenzhen'],
  'United States': ['New York', 'Seattle', 'Austin'],
  'United Kingdom': ['London', 'Manchester', 'Leeds'],
};

export default function mount(ctx: DemoContext) {
  const { lang } = ctx;
  const h = (en: string, ko: string) => tr(lang, { en, ko });
  const TAGS = [h('VIP', 'VIP'), h('New', '신규'), h('Wholesale', '도매'), h('Overseas', '해외')];
  const pad = (n: number) => String(n).padStart(2, '0');
  const data = makeRows(300).map(r => {
    const m = 1 + (r.id % 12);
    return {
      ...r,
      city: CITIES[r.country][r.id % 3],
      period: `2026-${pad(m)}-01 ~ 2026-${pad(m)}-${pad(10 + (r.id % 18))}`,
      plan: ['Free', 'Pro', 'Team'][r.id % 3],
      tags: TAGS.filter((_, i) => (r.id >> i) & 1),
      phone: `010-${String(1000 + ((r.id * 37) % 9000))}-${String(1000 + ((r.id * 91) % 9000))}`,
      rating: (r.id % 11) / 2,
      newsletter: r.id % 4 ? 'Y' : 'N',
      memo: r.id % 5 ? '' : h('Call before delivery.\nLeave at the front desk.', '배송 전 전화 주세요.\n프런트에 맡겨 주세요.'),
    };
  });
  const columns: ColumnDef[] = [
    { field: 'id', header: 'ID', type: 'number', format: '0', width: 70, pinned: 'left' },
    // text editor + required
    { field: 'name', header: h('Name', '이름'), width: 170, editable: true, required: true },
    // combo: type to filter the list; free: false keeps out values that are not listed
    { field: 'country', header: h('Country', '국가'), width: 150, editable: true,
      editor: { type: 'combo', options: Object.keys(CITIES), free: false } },
    // dependent select: options come from the row's country
    // a city the new country does not have is cleared (dependsOn), blank cities show the placeholder
    { field: 'city', header: h('City', '도시'), width: 130, editable: true, dependsOn: ['country'],
      editor: { type: 'select', placeholder: h('Choose…', '선택…'), options: (row: Row) => CITIES[row.country] ?? [] } },
    // number editor + validation
    { field: 'q1', header: h('Q1 revenue', '1분기 매출'), type: 'number', format: '#,##0', width: 130, editable: true,
      validate: v => (v == null || (typeof v === 'number' && v >= 0) ? true : h('Must be 0 or more', '0 이상이어야 합니다')) },
    // date columns open a calendar; typing a date still works
    { field: 'joined', header: h('Joined', '가입일'), type: 'date', width: 130, editable: true },
    // two-month calendar with presets (last 7 days, this month …)
    { field: 'period', header: h('Contract period', '계약 기간'), width: 210, editable: true, editor: { type: 'dateRange' } },
    { field: 'plan', header: h('Plan', '요금제'), width: 90, editable: true, editor: { type: 'radio', options: ['Free', 'Pro', 'Team'] } },
    { field: 'tags', header: h('Tags', '태그'), width: 170, editable: true, editor: { type: 'multiSelect', options: TAGS } },
    // formatted as you type: 010-1234-5678, 02-123-4567
    { field: 'phone', header: h('Phone', '전화번호'), width: 140, editable: true, editor: { type: 'mask', mask: 'phone' } },
    { field: 'rating', header: h('Rating', '평점'), type: 'number', format: '0.0', width: 90, editable: true,
      editor: { type: 'number', min: 0, max: 5, step: 0.5 } },
    { field: 'newsletter', header: h('Newsletter', '뉴스레터'), width: 110, editable: true, headerCheckbox: true, editor: { type: 'toggle', on: 'Y', off: 'N' } },
    { field: 'active', header: h('Active', '활성'), type: 'boolean', width: 90, editable: true }, // Space or double-click toggles
    // one click opens a dialog for long text
    { field: 'memo', header: h('Memo', '메모'), width: 180, editable: true, singleClickEdit: true,
      editor: { type: 'modal', title: h('Delivery memo', '배송 메모'), maxLength: 500 } },
    { field: 'email', header: h('Email (read-only)', '이메일 (읽기 전용)'), width: 260 },
  ];
  const grid = createGrid(ctx.host, {
    columns, data, rowSelection: 'multiple', locale: lang,
    getRowId: r => String(r.id),
    // right-click a cell: Add note… (a red corner marks it; hover to read)
    cellNotes: true,
    notes: [{ rowId: '3', colId: 'name', note: h('VIP customer: call before shipping', 'VIP 고객: 출고 전 전화') }],
  });

  grid.on('cellValueChanged', e => ctx.log(`cellValueChanged → ${e.colId}: ${String(e.oldValue)} → ${String(e.newValue)}`));
  grid.on('validationFailed', e => ctx.log(`validationFailed → ${e.colId}: ${e.message}`));
  grid.on('rowsAdded', e => ctx.log(`rowsAdded → ${e.rows.length}`));
  grid.on('rowsRemoved', e => ctx.log(`rowsRemoved → ${e.rows.length}`));

  text(ctx, h('Double-click, press Enter or just type. Enter saves, Esc cancels, Tab moves on. Switches flip with one click; Memo opens a dialog.',
    '더블클릭하거나 Enter를 누르거나 바로 입력하세요. Enter로 저장, Esc로 취소, Tab으로 다음 칸. 스위치는 한 번 클릭으로, 메모는 클릭하면 창이 열립니다.'));
  separator(ctx);
  button(ctx, h('Add row', '행 추가'), () => {
    const [row] = grid.addRows([{ id: 1000 + grid.getData().length, name: '', country: 'South Korea', city: 'Seoul', q1: 0, active: true }], 0);
    grid.scrollToRow(0);
    grid.startEdit(0, 'name');
    return row;
  });
  button(ctx, h('Delete selected', '선택 행 삭제'), () => grid.removeSelectedRows());
  button(ctx, h('Undo', '실행 취소'), () => grid.undo());
  button(ctx, h('Redo', '다시 실행'), () => grid.redo());
  separator(ctx);
  button(ctx, h('Show changes', '변경 내역 보기'), () => {
    const m = grid.getModifiedRows();
    ctx.log(h(`created ${m.created.length}, updated ${m.updated.length}, deleted ${m.deleted.length}`,
      `추가 ${m.created.length}, 수정 ${m.updated.length}, 삭제 ${m.deleted.length}`));
    for (const c of grid.getChanges().slice(0, 10)) ctx.log(`  #${c.row.id} ${c.colId}: ${String(c.oldValue)} → ${String(c.newValue)}`);
  });
  button(ctx, h('Save (commit)', '저장 (commit)'), () => {
    grid.commitChanges();
    ctx.log(h('changes committed — this is where you would send them to your server', '변경 확정 — 실제로는 여기서 서버로 보냅니다'));
  });
  button(ctx, h('Revert all', '모두 되돌리기'), () => grid.revertChanges());
  return grid;
}

Mark a column editable: true and users can edit its cells: double-click, press Enter or F2, or just start typing. Enter saves and moves down, Tab saves and moves to the next editable cell, Esc cancels. Booleans toggle with Space or a double-click. Typing with an input method (Korean, Japanese, Chinese) starts the edit the same way and the composition carries on in the editor; an Enter that finishes a composition only finishes it, and the next Enter saves.

The editor follows the column type: text, numbers (1,234 is accepted), dates (a calendar) and booleans. editor picks another one: a select for a fixed list, a textarea for long text, a time or date-time picker ('time', 'datetime'), or one of the editors below. When a select's options is a function of the row you get dependent selects, such as cities by country, and an option with disabled: true can be neither chosen nor pasted. editable can also be a function that decides per cell, for example to lock closed orders.

const COUNTRIES = { KR: ['Seoul', 'Busan'], JP: ['Tokyo', 'Osaka'] };

const grid = createGrid(el, {
  columns: [
    { field: 'id', type: 'number' },                                   // read-only
    { field: 'name', editable: true },
    { field: 'qty', type: 'number', editable: ({ row }) => !row.locked }, // per cell
    { field: 'country', editable: true, editor: { type: 'select', options: Object.keys(COUNTRIES) } },
    { field: 'city', editable: true, editor: { type: 'select', options: row => COUNTRIES[row.country] } },
    { field: 'status', editable: true, editor: { type: 'select', options: [
      { value: 'open' }, { value: 'closed', label: 'Closed (admin only)', disabled: true } ] } },
    { field: 'memo', editable: true, editor: { type: 'textarea' } },
    { field: 'pickup', editable: true, editor: { type: 'time' } },
    { field: 'active', type: 'boolean', editable: true },             // Space / double-click toggles
  ],
  data,
  editType: 'cell',   // or 'row': Tab stays in the row, Enter saves it, Escape puts it back
});

grid.startEdit(0, 'name');   // open an editor from code
grid.stopEdit();             // save it (stopEdit(true) cancels)

// stop a change before it happens
grid.on('beforeEdit', e => { if (e.row.locked) e.cancel(); });
grid.on('beforeCellChange', e => { if (e.newValue < 0) e.cancel(); });
grid.on('cellValueChanged', e => console.log(e.colId, e.oldValue, '→', e.newValue));

startEdit(rowIndex, colId) and stopEdit() open and close an editor from code. editStart and editStop report it, and cellValueChanged fires after every change, once the row holds the new value. Call cancel() in beforeEdit to keep an editor from opening, or in beforeCellChange to refuse a value from an edit, a paste or Delete.

Editors

Pick an editor with editor: { type }. Pasting, fill and Delete follow the same rules, and the cell shows option labels and formatted values. singleClickEdit: true opens an editor with one click. Each editor has its own page with a live example and all its options:

Cascading selects and column checkboxes

dependsOn clears a value that its parent no longer offers, and headerCheckbox switches a whole column at once. Both are explained with an example on:

Cell notes

With cellNotes: true a right-click adds, edits or deletes a note on a cell. See:

Editing a whole row

With editType: 'row' a row is edited as a whole: Tab stays in the row, Enter or moving to another row saves it (rowEditStop lists the changed cells), and Escape puts the whole row back. stopRowEdit() finishes the row from code.

To keep bad values out and to send only what changed to your server, see Validation and change tracking. Cells that hold formulas such as =qty*price are on Formulas.

Changes from outside

For changes that come from outside, such as a websocket, use applyTransaction to add, update and remove rows by id. Changed cells flash, and nothing goes into undo or the change log. When updates arrive often, applyTransactionAsync merges them into one redraw; see Real-time updates.

// prices pushed from a websocket: changed cells flash
socket.onmessage = e => grid.applyTransactionAsync({ update: JSON.parse(e.data) });

// add, update and remove by id
grid.applyTransaction({ add: [newOrder], addIndex: 0, update: [{ id: 7, status: 'done' }], remove: [{ id: 3 }] });

Questions about this page

How do I make cells editable in FreeGrid?

Set editable: true on a column (or a function per cell). Text, number, date, select, time and textarea editors are built in, with validation, undo and change tracking for saving.