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

수량 편집기: − 숫자 + 버튼으로 바꾸기Quantity editor with − and + buttons

숫자 칸을 편집할 때 −, + 버튼과 위·아래 화살표 키로 한 칸씩 바꿀 수 있는 편집기를 직접 만들어요. 범위(0~99)를 벗어나면 확정되지 않아요.Build an editor for number cells with − and + buttons and Up/Down arrow keys. A value outside 0–99 is not committed.

활용Intermediate
직접 써 보기Live preview수량 편집기: − 숫자 + 버튼으로 바꾸기Quantity editor with − and + buttons

코드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="edit">1번 줄 수량 편집</button>
  </div>
  <div id="grid" style="height: 240px"></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('edit').addEventListener('click', () => actions.edit(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 이유를 마우스를 올려야만 보이면 터치·키보드로는 놓쳐요. 표 바로 아래에 눈에 보이는 안내 줄도 둬요.
function makeReasonLine() {
  const line = document.createElement('div');
  line.setAttribute('role', 'status');
  line.style.cssText =
    'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
  document.getElementById('grid')?.after(line);
  // 안내가 없을 때는 자리를 차지하지 않는다(표와 로그 사이가 벌어져 보이지 않게). 줄 자체는 남겨 두어 상태 알림은 그대로 읽힌다.
  return {
    show: (text) => {
      line.textContent = text;
      line.style.marginTop = text ? '6px' : '0';
    },
    remove: () => line.remove(),
  };
}
// 폰처럼 손가락으로 쓰는 화면에서는 입력 글자를 16px로 해서, 입력칸을 누를 때 화면이 저절로 확대되지 않게 해요.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 숫자 증감 편집기: [−] 값 [+]. 위·아래 화살표 키로도 바꿔요. Enter(확정)와 Esc(취소)는 그리드가 맡고, 편집기는 값만 다뤄요.
const stepper = () => {
  let wrap;
  let input;
  const step = (delta) => {
    input.value = String(Math.max(0, (Number(input.value) || 0) + delta));
  };
  const button = (label, delta) => {
    const b = document.createElement('button');
    b.type = 'button';
    b.textContent = label;
    b.tabIndex = -1; // 포커스는 입력칸에 그대로 둬요
    b.setAttribute('aria-label', delta > 0 ? L('하나 늘리기', 'Increase by one') : L('하나 줄이기', 'Decrease by one'));
    b.style.cssText = `width: 40px; height: 100%; border: 0; background: transparent; font: inherit; cursor: pointer; color: inherit;`;
    b.addEventListener('mousedown', (e) => e.preventDefault()); // 입력칸의 포커스를 잃지 않게 해요
    b.addEventListener('click', () => step(delta));
    return b;
  };
  return {
    mount(el, ctx) {
      wrap = document.createElement('div');
      wrap.style.cssText = 'display: flex; height: 100%; align-items: center;';
      // −/+ 단추가 있으니 브라우저 기본 증감 화살표는 숨겨요(이 편집기 안에서만).
      const hideSpin = document.createElement('style');
      hideSpin.textContent =
        '.mxg-stepper-input{appearance:textfield;-moz-appearance:textfield}' +
          '.mxg-stepper-input::-webkit-inner-spin-button,.mxg-stepper-input::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}';
      wrap.append(hideSpin);
      input = document.createElement('input');
      input.className = 'mxg-stepper-input';
      input.type = 'number';
      input.setAttribute('aria-label', L(`${ctx.row.item} 수량`, `${ctx.row.item} quantity`));
      input.value = String(ctx.value ?? 0);
      input.style.cssText = `flex: 1; min-width: 0; height: 100%; border: 0; text-align: center; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
      input.addEventListener('keydown', (e) => {
        if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
          e.preventDefault();
          step(e.key === 'ArrowUp' ? 1 : -1);
        }
      });
      wrap.append(button('−', -1), input, button('+', 1));
      el.append(wrap);
    },
    getValue: () => (input.value === '' ? null : Number(input.value)),
    focus() {
      input.focus();
      input.select();
    },
    setError(message) {
      input.setAttribute('aria-invalid', String(message !== null));
      wrap.title = message ?? '';
    },
    destroy: () => wrap.remove(),
  };
};
export const options = {
  columns: [
    { id: 'item', title: '품목', width: 180 },
    {
      id: 'qty',
      title: '수량(더블클릭)',
      kind: 'number',
      width: 190,
      align: 'center',
      editable: true,
      cellEditor: stepper,
      validation: {
        custom: (value) => {
          const n = Number(value);
          if (value === null || Number.isNaN(n))
            return L('수량을 적어 주세요.', 'Enter a quantity.');
          return n < 0 || n > 99
            ? L('수량은 0에서 99 사이로 적어 주세요.', 'Enter a quantity between 0 and 99.')
            : null;
        },
      },
    },
  ],
  rows: [
    { id: 1, item: 'USB-C 케이블', qty: 12 },
    { id: 2, item: '무선 마우스', qty: 4 },
    { id: 3, item: '노트북 받침대', qty: 0 },
  ],
  rowKey: 'id',
  saveMode: 'none',
  rowHeight: coarse() ? 44 : 40,
};
export function setup(api, log) {
  const reason = makeReasonLine();
  log({
    ko: '수량 칸을 더블클릭하고 − + 버튼이나 위·아래 화살표 키로 바꿔 보세요.',
    en: 'Double-click a quantity cell and change it with the − + buttons or the up and down arrow keys.',
  });
  const offs = [
    api.on('editCancelled', () => reason.show('')),
    api.on('editCommitted', (e) => {
      reason.show('');
      log({
        ko: `${e.rowKey}번 줄 수량: ${String(e.oldValue)} → ${String(e.newValue)}`,
        en: `Row ${e.rowKey} quantity: ${String(e.oldValue)} → ${String(e.newValue)}`,
      });
    }),
    api.on('validationFailed', (e) => {
      reason.show(L(`✗ ${e.rowKey}번 줄 수량: ${e.message}`, `✗ Row ${e.rowKey} quantity: ${e.message}`));
      log({
        ko: `✗ ${e.rowKey}번 줄 수량: ${e.message}`,
        en: `✗ Row ${e.rowKey} quantity: ${e.message}`,
      });
    }),
  ];
  return () => {
    offs.forEach((off) => off());
    reason.remove();
  };
}
export const actions = {
  edit: (api) => api.startEdit(1, 'qty'),
};

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="edit">Edit quantity of row 1</button>
  </div>
  <div id="grid" style="height: 240px"></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('edit').addEventListener('click', () => actions.edit(api));
example.js
// A reason shown only on hover is missed on touch and keyboard, so also put a visible line right under the grid.
function makeReasonLine() {
  const line = document.createElement('div');
  line.setAttribute('role', 'status');
  line.style.cssText =
    'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
  document.getElementById('grid')?.after(line);
  // With no message the line takes no space (so the gap between grid and log does not widen). The line itself stays, so status announcements are still read.
  return {
    show: (text) => {
      line.textContent = text;
      line.style.marginTop = text ? '6px' : '0';
    },
    remove: () => line.remove(),
  };
}
// On finger-driven screens such as phones, input text is 16px so the page does not zoom when an input is tapped.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Number stepper editor: [−] value [+]. Up/Down arrow keys also change it. The grid handles Enter (commit) and Esc (cancel); the editor only handles the value.
const stepper = () => {
  let wrap;
  let input;
  const step = (delta) => {
    input.value = String(Math.max(0, (Number(input.value) || 0) + delta));
  };
  const button = (label, delta) => {
    const b = document.createElement('button');
    b.type = 'button';
    b.textContent = label;
    b.tabIndex = -1; // keep focus on the input
    b.setAttribute('aria-label', delta > 0 ? 'Increase by one' : 'Decrease by one');
    b.style.cssText = `width: 40px; height: 100%; border: 0; background: transparent; font: inherit; cursor: pointer; color: inherit;`;
    b.addEventListener('mousedown', (e) => e.preventDefault()); // do not steal focus from the input
    b.addEventListener('click', () => step(delta));
    return b;
  };
  return {
    mount(el, ctx) {
      wrap = document.createElement('div');
      wrap.style.cssText = 'display: flex; height: 100%; align-items: center;';
      // There are −/+ buttons, so hide the browser's default spin arrows (inside this editor only).
      const hideSpin = document.createElement('style');
      hideSpin.textContent =
        '.mxg-stepper-input{appearance:textfield;-moz-appearance:textfield}' +
          '.mxg-stepper-input::-webkit-inner-spin-button,.mxg-stepper-input::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}';
      wrap.append(hideSpin);
      input = document.createElement('input');
      input.className = 'mxg-stepper-input';
      input.type = 'number';
      input.setAttribute('aria-label', `${ctx.row.item} quantity`);
      input.value = String(ctx.value ?? 0);
      input.style.cssText = `flex: 1; min-width: 0; height: 100%; border: 0; text-align: center; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
      input.addEventListener('keydown', (e) => {
        if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
          e.preventDefault();
          step(e.key === 'ArrowUp' ? 1 : -1);
        }
      });
      wrap.append(button('−', -1), input, button('+', 1));
      el.append(wrap);
    },
    getValue: () => (input.value === '' ? null : Number(input.value)),
    focus() {
      input.focus();
      input.select();
    },
    setError(message) {
      input.setAttribute('aria-invalid', String(message !== null));
      wrap.title = message ?? '';
    },
    destroy: () => wrap.remove(),
  };
};
export const options = {
  columns: [
    { id: 'item', title: 'Item', width: 180 },
    {
      id: 'qty',
      title: 'Quantity (double-click)',
      kind: 'number',
      width: 240,
      align: 'center',
      editable: true,
      cellEditor: stepper,
      validation: {
        custom: (value) => {
          const n = Number(value);
          if (value === null || Number.isNaN(n))
            return 'Enter a quantity.';
          return n < 0 || n > 99 ? 'Enter a quantity between 0 and 99.' : null;
        },
      },
    },
  ],
  rows: [
    { id: 1, item: 'USB-C cable', qty: 12 },
    { id: 2, item: 'Wireless mouse', qty: 4 },
    { id: 3, item: 'Laptop stand', qty: 0 },
  ],
  rowKey: 'id',
  saveMode: 'none',
  rowHeight: coarse() ? 44 : 40,
};
export function setup(api, log) {
  const reason = makeReasonLine();
  log('Double-click a quantity cell and change it with the − + buttons or the up and down arrow keys.');
  const offs = [
    api.on('editCancelled', () => reason.show('')),
    api.on('editCommitted', (e) => {
      reason.show('');
      log(`Row ${e.rowKey} quantity: ${String(e.oldValue)} → ${String(e.newValue)}`);
    }),
    api.on('validationFailed', (e) => {
      reason.show(`✗ Row ${e.rowKey} quantity: ${e.message}`);
      log(`✗ Row ${e.rowKey} quantity: ${e.message}`);
    }),
  ];
  return () => {
    offs.forEach((off) => off());
    reason.remove();
  };
}
export const actions = {
  edit: (api) => api.startEdit(1, 'qty'),
};