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

금액 범위와 기간으로 거르기Filter by amount range and date period

금액은 최소·최대, 날짜는 시작일·종료일로 범위를 걸러요. 한쪽만 쓰면 '이상'이나 '이하', 둘 다 쓰면 '사이'(양 끝 포함)가 되고, 두 범위를 함께 걸면 둘 다 만족하는 행만 남아요.Filter amounts by min and max and dates by start and end. One side means at least or at most, both mean between (inclusive), and both ranges combine.

입문Beginner
직접 써 보기Live preview금액 범위와 기간으로 거르기Filter by amount range and date period

코드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">
    <input type="text" aria-label="최소 금액" placeholder="최소 금액" id="min" />
    <input type="text" aria-label="최대 금액" placeholder="최대 금액" id="max" />
    <input
      type="text"
      aria-label="시작일"
      placeholder="시작일 YYYY-MM-DD"
      id="from"
    />
    <input type="text" aria-label="종료일" placeholder="종료일 YYYY-MM-DD" id="to" />
  </div>
  <div id="grid" style="height: 560px"></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('min').addEventListener('input', (event) => actions.min(api, event.target.value));
document.getElementById('max').addEventListener('input', (event) => actions.max(api, event.target.value));
document.getElementById('from').addEventListener('input', (event) => actions.from(api, event.target.value));
document.getElementById('to').addEventListener('input', (event) => actions.to(api, event.target.value));
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const titles = [
  '사무용품 정기 구매',
  '서버 호스팅 갱신',
  '프린터 토너',
  '워크숍 대관',
  '출장 항공권',
  '모니터 교체',
  '교육 수강료',
  '광고 집행비',
];
const text = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
export const options = {
  columns: [
    { id: 'title', title: '내역', width: 180 },
    {
      id: 'amount',
      title: '금액(원)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('ko-KR'),
    },
    {
      id: 'ordered',
      title: '주문일',
      kind: 'date',
      width: 130,
      formatValue: (value) => (value instanceof Date ? text(value) : ''),
    },
  ],
  rows: Array.from({ length: 16 }, (_, i) => ({
    id: i + 1,
    title: titles[i % 8],
    amount: 30000 + ((i * 187000) % 900000),
    ordered: new Date(2026, i % 6, 3 + ((i * 7) % 24)),
  })),
  rowKey: 'id',
};
// 범위는 한쪽만 써도 돼요: 최소만 쓰면 '이상', 최대만 쓰면 '이하', 둘 다 쓰면 '사이'(양 끝 포함)예요.
// 날짜는 YYYY-MM-DD로 쓰고, 달력 날짜(시각 없음) 기준이에요.
const range = { min: '', max: '', from: '', to: '' };
let say = () => { };
const DATE = /^\d{4}-\d{2}-\d{2}$/;
const asDate = (value) => {
  if (!DATE.test(value))
    return null;
  const [y, m, d] = value.split('-').map(Number);
  const date = new Date(y, m - 1, d);
  return date.getMonth() === m - 1 && date.getDate() === d ? date : null;
};
function between(columnId, low, high) {
  if (low !== null && high !== null)
    return [{ columnId, operator: 'between', value: [low, high] }];
  if (low !== null)
    return [{ columnId, operator: 'gte', value: low }];
  if (high !== null)
    return [{ columnId, operator: 'lte', value: high }];
  return [];
}
const parseNum = (text) => {
  const t = text.replace(/,/g, '').trim();
  if (t === '')
    return null;
  return Number.isFinite(Number(t)) ? Number(t) : 'bad';
};
const parseDate = (text) => text === '' ? null : (asDate(text) ?? 'bad');
/** 입력칸에 잘못됐다는 표시(aria-invalid)를 켜고 끈다. */
const mark = (id, bad) => {
  const input = document.getElementById(id);
  if (!input)
    return;
  if (bad)
    input.setAttribute('aria-invalid', 'true');
  else
    input.removeAttribute('aria-invalid');
};
let lastNote = '';
/** 한 쌍(최소·최대 또는 시작·종료)을 검사해 걸 항목과 안내 문구를 돌려준다. 잘못되면 그 쌍은 걸지 않는다. */
function pair(column, ids, values, words) {
  const [low, high] = values;
  const bad = [low === 'bad', high === 'bad'];
  let note = bad[0] || bad[1] ? words.format : '';
  if (!note && low !== null && high !== null && Number(low) > Number(high)) {
    bad[0] = bad[1] = true;
    note = words.order;
  }
  mark(ids[0], bad[0]);
  mark(ids[1], bad[1]);
  if (note)
    return { items: [], note };
  return { items: between(column, low, high), note: '' };
}
function apply(api) {
  const amount = pair('amount', ['min', 'max'], [parseNum(range.min), parseNum(range.max)], {
    format: L('금액은 숫자로 써 주세요. 예: 200000', 'Write the amount as a number. Example: 200000'),
    order: L('최소 금액이 최대 금액보다 커요. 이 조건은 걸지 않았어요.', 'The minimum amount is greater than the maximum. This condition was not applied.'),
  });
  const period = pair('ordered', ['from', 'to'], [parseDate(range.from), parseDate(range.to)], {
    format: L('날짜는 YYYY-MM-DD로 써 주세요. 예: 2026-03-01', 'Write the date as YYYY-MM-DD. Example: 2026-03-01'),
    order: L('시작일이 종료일보다 늦어요. 이 조건은 걸지 않았어요.', 'The start date is later than the end date. This condition was not applied.'),
  });
  const note = [amount.note, period.note].filter(Boolean).join(' / ');
  if (note && note !== lastNote)
    say(note);
  lastNote = note;
  const items = [...amount.items, ...period.items];
  api.setFilterModel(items.length ? { match: 'all', items } : null);
}
/** 조작 막대에 그리드 컨트롤 모양(mxg-controls)을 입혀서, aria-invalid인 입력칸이 테마의 오류 모양(빨간 테두리·아이콘)으로 보이게 한다. */
function styleControls() {
  document.querySelector('.toolbar')?.classList.add('mxg-controls');
}
export function setup(api, log) {
  styleControls();
  say = log;
  lastNote = '';
  Object.assign(range, { min: '', max: '', from: '', to: '' });
  const off = api.on('filterChanged', () => log({
    ko: `보이는 행 ${api.getVisibleRowCount()} / 전체 ${api.getRowCount()}`,
    en: `Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`,
  }));
  return () => off();
}
const setter = (key) => (api, value) => {
  range[key] = (value ?? '').trim();
  apply(api);
};
export const actions = {
  min: setter('min'),
  max: setter('max'),
  from: setter('from'),
  to: setter('to'),
};

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">
    <input
      type="text"
      aria-label="Min amount"
      placeholder="Min amount"
      id="min"
    />
    <input
      type="text"
      aria-label="Max amount"
      placeholder="Max amount"
      id="max"
    />
    <input
      type="text"
      aria-label="From"
      placeholder="From YYYY-MM-DD"
      id="from"
    />
    <input type="text" aria-label="To" placeholder="To YYYY-MM-DD" id="to" />
  </div>
  <div id="grid" style="height: 560px"></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('min').addEventListener('input', (event) => actions.min(api, event.target.value));
document.getElementById('max').addEventListener('input', (event) => actions.max(api, event.target.value));
document.getElementById('from').addEventListener('input', (event) => actions.from(api, event.target.value));
document.getElementById('to').addEventListener('input', (event) => actions.to(api, event.target.value));
example.js
const titles = [
  'Office supplies restock',
  'Server hosting renewal',
  'Printer toner',
  'Workshop venue',
  'Business trip flight',
  'Monitor replacement',
  'Training course fee',
  'Ad spend',
];
const text = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
export const options = {
  columns: [
    { id: 'title', title: 'Description', width: 200 },
    {
      id: 'amount',
      title: 'Amount ($)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
    },
    {
      id: 'ordered',
      title: 'Ordered',
      kind: 'date',
      width: 130,
      formatValue: (value) => (value instanceof Date ? text(value) : ''),
    },
  ],
  rows: Array.from({ length: 16 }, (_, i) => ({
    id: i + 1,
    title: titles[i % 8],
    amount: 30 + ((i * 187) % 900),
    ordered: new Date(2026, i % 6, 3 + ((i * 7) % 24)),
  })),
  rowKey: 'id',
};
// A range can have just one side: min only means "at least", max only means "at most", both mean "between" (ends included).
// Dates are written as YYYY-MM-DD and compared as calendar dates (no time of day).
const range = { min: '', max: '', from: '', to: '' };
let say = () => { };
const DATE = /^\d{4}-\d{2}-\d{2}$/;
const asDate = (value) => {
  if (!DATE.test(value))
    return null;
  const [y, m, d] = value.split('-').map(Number);
  const date = new Date(y, m - 1, d);
  return date.getMonth() === m - 1 && date.getDate() === d ? date : null;
};
function between(columnId, low, high) {
  if (low !== null && high !== null)
    return [{ columnId, operator: 'between', value: [low, high] }];
  if (low !== null)
    return [{ columnId, operator: 'gte', value: low }];
  if (high !== null)
    return [{ columnId, operator: 'lte', value: high }];
  return [];
}
const parseNum = (text) => {
  const t = text.replace(/,/g, '').trim();
  if (t === '')
    return null;
  return Number.isFinite(Number(t)) ? Number(t) : 'bad';
};
const parseDate = (text) => text === '' ? null : (asDate(text) ?? 'bad');
/** Turns the invalid mark (aria-invalid) on or off for an input. */
const mark = (id, bad) => {
  const input = document.getElementById(id);
  if (!input)
    return;
  if (bad)
    input.setAttribute('aria-invalid', 'true');
  else
    input.removeAttribute('aria-invalid');
};
let lastNote = '';
/** Checks one pair (min/max or from/to) and returns the items to apply and a message. An invalid pair is not applied. */
function pair(column, ids, values, words) {
  const [low, high] = values;
  const bad = [low === 'bad', high === 'bad'];
  let note = bad[0] || bad[1] ? words.format : '';
  if (!note && low !== null && high !== null && Number(low) > Number(high)) {
    bad[0] = bad[1] = true;
    note = words.order;
  }
  mark(ids[0], bad[0]);
  mark(ids[1], bad[1]);
  if (note)
    return { items: [], note };
  return { items: between(column, low, high), note: '' };
}
function apply(api) {
  const amount = pair('amount', ['min', 'max'], [parseNum(range.min), parseNum(range.max)], {
    format: 'Write the amount as a number. Example: 200',
    order: 'The minimum amount is greater than the maximum. This condition was not applied.',
  });
  const period = pair('ordered', ['from', 'to'], [parseDate(range.from), parseDate(range.to)], {
    format: 'Write the date as YYYY-MM-DD. Example: 2026-03-01',
    order: 'The start date is later than the end date. This condition was not applied.',
  });
  const note = [amount.note, period.note].filter(Boolean).join(' / ');
  if (note && note !== lastNote)
    say(note);
  lastNote = note;
  const items = [...amount.items, ...period.items];
  api.setFilterModel(items.length ? { match: 'all', items } : null);
}
/** Gives the toolbar the grid control look (mxg-controls) so inputs with aria-invalid show the theme's error style (red border, icon). */
function styleControls() {
  document.querySelector('.toolbar')?.classList.add('mxg-controls');
}
export function setup(api, log) {
  styleControls();
  say = log;
  lastNote = '';
  Object.assign(range, { min: '', max: '', from: '', to: '' });
  const off = api.on('filterChanged', () => log(`Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`));
  return () => off();
}
const setter = (key) => (api, value) => {
  range[key] = (value ?? '').trim();
  apply(api);
};
export const actions = {
  min: setter('min'),
  max: setter('max'),
  from: setter('from'),
  to: setter('to'),
};