본문으로 건너뛰기Skip to content
예제 첫화면Examples home

고른 줄에 한꺼번에 적용하기Apply a change to all selected rows

줄을 여러 개 골라 상태·우선순위를 한 번에 바꾸고, 맨 위 줄의 담당자를 나머지에 채우고, 모두 1시간씩 더할 수 있어요. 여러 줄을 한 번에 고쳐도 변경 기록에는 한 묶음으로 남아서 저장 전에 한꺼번에 버릴 수 있어요.Pick several rows and change status or priority at once, fill the top row's owner into the rest, or add an hour to all. Even a multi-row change is one batch in the change log, so you can discard it before saving.

활용Intermediate
직접 써 보기Live preview고른 줄에 한꺼번에 적용하기Apply a change to all selected rows

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="selectAll">전체 선택</button>
    <select aria-label="상태 바꾸기" id="status">
      <option value="pick" selected>(고르세요)</option>
      <option value="open">접수</option>
      <option value="doing">진행</option>
      <option value="done">완료</option>
    </select>
    <select aria-label="우선순위 바꾸기" id="priority">
      <option value="pick" selected>(고르세요)</option>
      <option value="low">낮음</option>
      <option value="high">높음</option>
    </select>
    <button type="button" id="fillOwner">담당자 아래로 채우기</button>
    <button type="button" id="addHour">시간 +1</button>
    <button type="button" id="discard">변경 버리기</button>
  </div>
  <div id="grid" style="height: 290px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('selectAll').addEventListener('click', () => actions.selectAll(api));
document.getElementById('status').addEventListener('change', (event) => actions.status(api, event.target.value));
document.getElementById('priority').addEventListener('change', (event) => actions.priority(api, event.target.value));
document.getElementById('fillOwner').addEventListener('click', () => actions.fillOwner(api));
document.getElementById('addHour').addEventListener('click', () => actions.addHour(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
example.js
const tickets = [
  '로그인 이동 오류',
  '푸터 링크 정리',
  '검색 결과가 느려요',
  '가격표 오타',
  'Safari에서 내보내기 실패',
  '알림 설정 저장 안 됨',
];
const rows = tickets.map((ticket, i) => ({
  id: i + 1,
  ticket,
  owner: i === 0 ? '김서연' : '',
  status: 'open',
  priority: i % 2 ? 'high' : 'low',
  hours: i === 0 ? 3 : 0,
}));
const statusName = { open: '접수', doing: '진행', done: '완료' };
const priorityName = { low: '낮음', high: '높음' };
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word) => {
  const ch = word.trim().slice(-1);
  const digit = '0123456789'.indexOf(ch);
  if (digit >= 0)
    return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0; // 영 일 이 삼 사 오 육 칠 팔 구
  const code = ch.charCodeAt(0) - 0xac00;
  return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const eulReul = (word) => (batchim(word) ? '을' : '를');
const euroRo = (word) => (batchim(word) && batchim(word) !== 8 ? '으로' : '로');
export const options = {
  columns: [
    { id: 'ticket', title: '티켓', width: 180 },
    { id: 'owner', title: '담당자', width: 100, editable: true },
    {
      id: 'status',
      title: '상태',
      width: 80,
      formatValue: (v) => statusName[String(v)] ?? String(v),
    },
    {
      id: 'priority',
      title: '우선순위',
      width: 90,
      formatValue: (v) => priorityName[String(v)] ?? String(v),
    },
    { id: 'hours', title: '시간', kind: 'number', width: 80, align: 'end', editable: true },
  ],
  rows,
  rowKey: 'id',
  selection: { mode: 'multiple', checkbox: true },
  saveMode: 'batch',
};
let say = () => { };
export function setup(api, log) {
  say = log;
  log({
    ko: '왼쪽 체크박스로 줄을 고른 뒤 위의 버튼이나 선택 상자를 써 보세요.',
    en: 'Select rows with the checkboxes on the left, then use the buttons or selects above.',
  });
  return api.on('changesCountChanged', ({ count }) => log({ ko: `저장 안 한 변경: ${count}줄`, en: `Unsaved changes: ${count} rows` }));
}
const selectedRows = (api) => api.getSelectedKeys().flatMap((key) => {
  const row = api.getRowByKey(key);
  return row ? [row] : [];
});
// 여러 줄을 고칠 때는 updateRows를 한 번만 불러요. 그러면 변경 기록에 한 묶음으로 남아서 저장 전에 한꺼번에 검토하거나 버릴 수 있어요.
function setSelected(api, column, value, names) {
  if (!value || value === 'pick')
    return;
  // 같은 값을 또 고를 수 있게 선택 상자를 "(고르세요)"로 되돌려요(선택 상자의 id는 컨트롤 id와 같아요).
  const box = document.getElementById(column);
  if (box instanceof HTMLSelectElement)
    box.value = 'pick';
  const rows = selectedRows(api);
  if (!rows.length)
    return say({ ko: '먼저 줄을 하나 이상 골라 주세요.', en: 'Select at least one row first.' });
  const n = api.updateRows(rows.map((row) => ({ ...row, [column]: value })));
  say({
    ko: `${n}줄의 ${column === 'status' ? '상태' : '우선순위'}를 "${names[value] ?? value}"${euroRo(names[value] ?? value)} 바꿨어요.`,
    en: `Set ${column === 'status' ? 'status' : 'priority'} of ${n} rows to "${names[value] ?? value}".`,
  });
}
export const actions = {
  status: (api, value) => setSelected(api, 'status', value, statusName),
  priority: (api, value) => setSelected(api, 'priority', value, priorityName),
  // 아래로 채우기: 고른 줄 중 맨 위 줄의 담당자를 나머지 고른 줄에 복사해요(엑셀의 Ctrl+D처럼).
  fillOwner: (api) => {
    const [first, ...rest] = selectedRows(api);
    if (!first || !rest.length)
      return say({
        ko: '두 줄 이상 골라 주세요. 맨 위 줄의 값이 나머지에 채워져요.',
        en: 'Select two or more rows. The value of the top row is filled into the rest.',
      });
    const n = api.updateRows(rest.map((row) => ({ ...row, owner: first.owner })));
    say({
      ko: `"${first.owner || '(빈 값)'}"${eulReul(first.owner || '값')} ${n}줄에 채웠어요.`,
      en: `Filled "${first.owner || '(empty)'}" into ${n} rows.`,
    });
  },
  addHour: (api) => {
    const rows = selectedRows(api);
    if (!rows.length)
      return say({ ko: '먼저 줄을 하나 이상 골라 주세요.', en: 'Select at least one row first.' });
    say({
      ko: `${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))}줄에 1시간씩 더했어요.`,
      en: `Added 1 hour to ${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))} rows.`,
    });
  },
  selectAll: (api) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
  discard: (api) => {
    api.rollbackChanges();
    api.setSelectedKeys([]);
  },
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="selectAll">Select all</button>
    <select aria-label="Set status" id="status">
      <option value="pick" selected>(pick one)</option>
      <option value="open">Open</option>
      <option value="doing">In progress</option>
      <option value="done">Done</option>
    </select>
    <select aria-label="Set priority" id="priority">
      <option value="pick" selected>(pick one)</option>
      <option value="low">Low</option>
      <option value="high">High</option>
    </select>
    <button type="button" id="fillOwner">Fill owner down</button>
    <button type="button" id="addHour">Add 1 hour</button>
    <button type="button" id="discard">Discard changes</button>
  </div>
  <div id="grid" style="height: 290px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('selectAll').addEventListener('click', () => actions.selectAll(api));
document.getElementById('status').addEventListener('change', (event) => actions.status(api, event.target.value));
document.getElementById('priority').addEventListener('change', (event) => actions.priority(api, event.target.value));
document.getElementById('fillOwner').addEventListener('click', () => actions.fillOwner(api));
document.getElementById('addHour').addEventListener('click', () => actions.addHour(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
example.js
const tickets = [
  'Login redirect error',
  'Tidy footer links',
  'Search results are slow',
  'Typo in price list',
  'Export fails in Safari',
  'Notification settings not saved',
];
const rows = tickets.map((ticket, i) => ({
  id: i + 1,
  ticket,
  owner: i === 0 ? 'Liam Carter' : '',
  status: 'open',
  priority: i % 2 ? 'high' : 'low',
  hours: i === 0 ? 3 : 0,
}));
const statusName = { open: 'Open', doing: 'In progress', done: 'Done' };
const priorityName = { low: 'Low', high: 'High' };
export const options = {
  columns: [
    { id: 'ticket', title: 'Ticket', width: 230 },
    { id: 'owner', title: 'Owner', width: 120, editable: true },
    {
      id: 'status',
      title: 'Status',
      width: 110,
      formatValue: (v) => statusName[String(v)] ?? String(v),
    },
    {
      id: 'priority',
      title: 'Priority',
      width: 90,
      formatValue: (v) => priorityName[String(v)] ?? String(v),
    },
    { id: 'hours', title: 'Hours', kind: 'number', width: 80, align: 'end', editable: true },
  ],
  rows,
  rowKey: 'id',
  selection: { mode: 'multiple', checkbox: true },
  saveMode: 'batch',
};
let say = () => { };
export function setup(api, log) {
  say = log;
  log('Select rows with the checkboxes on the left, then use the buttons or selects above.');
  return api.on('changesCountChanged', ({ count }) => log(`Unsaved changes: ${count} rows`));
}
const selectedRows = (api) => api.getSelectedKeys().flatMap((key) => {
  const row = api.getRowByKey(key);
  return row ? [row] : [];
});
// When editing several rows, call updateRows only once. The changes are then recorded as one batch, so they can be reviewed or discarded together before saving.
function setSelected(api, column, value, names) {
  if (!value || value === 'pick')
    return;
  // Reset the select to "(pick one)" so the same value can be chosen again (the select's id equals the control id).
  const box = document.getElementById(column);
  if (box instanceof HTMLSelectElement)
    box.value = 'pick';
  const rows = selectedRows(api);
  if (!rows.length)
    return say('Select at least one row first.');
  const n = api.updateRows(rows.map((row) => ({ ...row, [column]: value })));
  say(`Set ${column === 'status' ? 'status' : 'priority'} of ${n} rows to "${names[value] ?? value}".`);
}
export const actions = {
  status: (api, value) => setSelected(api, 'status', value, statusName),
  priority: (api, value) => setSelected(api, 'priority', value, priorityName),
  // Fill down: copy the owner of the top selected row to the other selected rows (like Ctrl+D in a spreadsheet).
  fillOwner: (api) => {
    const [first, ...rest] = selectedRows(api);
    if (!first || !rest.length)
      return say('Select two or more rows. The value of the top row is filled into the rest.');
    const n = api.updateRows(rest.map((row) => ({ ...row, owner: first.owner })));
    say(`Filled "${first.owner || '(empty)'}" into ${n} rows.`);
  },
  addHour: (api) => {
    const rows = selectedRows(api);
    if (!rows.length)
      return say('Select at least one row first.');
    say(`Added 1 hour to ${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))} rows.`);
  },
  selectAll: (api) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
  discard: (api) => {
    api.rollbackChanges();
    api.setSelectedKeys([]);
  },
};