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

키와 값으로 행을 코드에서 고르기Select rows by key or value from code

selectRows로 키 목록을 고르거나 더하고, selectWhere로 값 조건에 맞는 행을 고르고, deselectRows, getSelectedRows, isSelected로 풀거나 읽어요. 잠긴 행은 selectWhere가 건너뛰고 selectRows는 오류로 알려요.Select or add keys with selectRows, select rows matching a value with selectWhere, and deselect or read with deselectRows, getSelectedRows and isSelected. selectWhere skips locked rows while selectRows reports them as an error.

활용Intermediate
직접 써 보기Live preview키와 값으로 행을 코드에서 고르기Select rows by key or value from code

코드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="keys">키로 고르기(2, 4, 7)</button>
    <button type="button" id="add">키 더하기(3, 5)</button>
    <button type="button" id="where">값으로 고르기(팀 개발)</button>
    <button type="button" id="locked">잠긴 행 고르기</button>
    <button type="button" id="remove">2번 풀기</button>
    <button type="button" id="read">읽기</button>
    <button type="button" id="clear">모두 풀기</button>
  </div>
  <div id="grid" style="height: 460px"></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('keys').addEventListener('click', () => actions.keys(api));
document.getElementById('add').addEventListener('click', () => actions.add(api));
document.getElementById('where').addEventListener('click', () => actions.where(api));
document.getElementById('locked').addEventListener('click', () => actions.locked(api));
document.getElementById('remove').addEventListener('click', () => actions.remove(api));
document.getElementById('read').addEventListener('click', () => actions.read(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const teams = ['개발', '디자인', '영업'];
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희'];
// 키(id)나 값으로 행을 코드에서 고르고 풀어요. 잠긴 행(isRowSelectable이 false)은 selectWhere가 조용히 건너뛰고,
// selectRows는 잠긴 행을 주면 오류(invalid-option)로 알려 줘요.
export const options = {
  columns: [
    { id: 'team', title: '팀', width: 90 },
    { id: 'name', title: '이름', width: 100 },
    { id: 'score', title: '점수', kind: 'number', width: 90, align: 'end' },
  ],
  rows: Array.from({ length: 12 }, (_, i) => ({
    id: i + 1,
    team: teams[i % 3],
    name: names[i % 6],
    score: 55 + ((i * 17) % 45),
  })),
  rowKey: 'id',
  selection: { mode: 'multiple', checkbox: true },
  isRowSelectable: (row) => row.score >= 60,
};
let say = () => { };
export function setup(api, log) {
  say = log;
  const off = api.on('selectionChanged', ({ selectedKeys }) => log({
    ko: `선택 ${selectedKeys.length}개: ${selectedKeys.join(', ') || '없음'}`,
    en: `${selectedKeys.length} selected: ${selectedKeys.join(', ') || 'none'}`,
  }));
  log({
    ko: '점수가 60 아래인 행은 잠겨 있어요(체크할 수 없어요).',
    en: 'Rows with a score under 60 are locked and cannot be ticked.',
  });
  return () => off();
}
export const actions = {
  keys: (api) => api.selectRows([2, 4, 7]),
  add: (api) => api.selectRows([3, 5], { add: true }),
  where: (api) => {
    const count = api.selectWhere({ team: '개발' });
    say({
      ko: `팀이 개발인 행 중 고를 수 있는 ${count}개를 골랐어요(잠긴 행은 건너뛰어요).`,
      en: `Selected ${count} selectable rows in team 개발 (locked rows are skipped).`,
    });
  },
  locked: (api) => {
    const locked = api.findRows((row) => row.score < 60)[0];
    if (locked === undefined)
      return;
    try {
      api.selectRows([locked.id]);
    }
    catch (error) {
      say({
        ko: `잠긴 행은 selectRows로 고를 수 없어요: ${error.message}`,
        en: `A locked row cannot be selected with selectRows: ${error.message}`,
      });
    }
  },
  remove: (api) => api.deselectRows([2]),
  read: (api) => {
    const rows = api.getSelectedRows();
    say({
      ko: `getSelectedRows: ${rows.map((r) => r.name).join(', ') || '없음'} / 4번 행 선택됨: ${String(api.isSelected(4))}`,
      en: `getSelectedRows: ${rows.map((r) => r.name).join(', ') || 'none'} / row 4 selected: ${String(api.isSelected(4))}`,
    });
  },
  clear: (api) => api.deselectAllRows(),
};

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="keys">Select by key (2, 4, 7)</button>
    <button type="button" id="add">Add keys (3, 5)</button>
    <button type="button" id="where">Select by value (team Dev)</button>
    <button type="button" id="locked">Select a locked row</button>
    <button type="button" id="remove">Deselect row 2</button>
    <button type="button" id="read">Read</button>
    <button type="button" id="clear">Deselect all</button>
  </div>
  <div id="grid" style="height: 460px"></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('keys').addEventListener('click', () => actions.keys(api));
document.getElementById('add').addEventListener('click', () => actions.add(api));
document.getElementById('where').addEventListener('click', () => actions.where(api));
document.getElementById('locked').addEventListener('click', () => actions.locked(api));
document.getElementById('remove').addEventListener('click', () => actions.remove(api));
document.getElementById('read').addEventListener('click', () => actions.read(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const teams = ['Dev', 'Design', 'Sales'];
const names = [
  'Liam Carter',
  'Emma Stone',
  'Noah Reed',
  'Olivia Hayes',
  'Ethan Brooks',
  'Ava Morgan',
];
// Select and deselect rows in code by key (id) or by value. Locked rows (isRowSelectable is false) are silently skipped by selectWhere,
// while selectRows reports an error (invalid-option) if given a locked row.
export const options = {
  columns: [
    { id: 'team', title: 'Team', width: 90 },
    { id: 'name', title: 'Name', width: 130 },
    { id: 'score', title: 'Score', kind: 'number', width: 90, align: 'end' },
  ],
  rows: Array.from({ length: 12 }, (_, i) => ({
    id: i + 1,
    team: teams[i % 3],
    name: names[i % 6],
    score: 55 + ((i * 17) % 45),
  })),
  rowKey: 'id',
  selection: { mode: 'multiple', checkbox: true },
  isRowSelectable: (row) => row.score >= 60,
};
let say = () => { };
export function setup(api, log) {
  say = log;
  const off = api.on('selectionChanged', ({ selectedKeys }) => log(`${selectedKeys.length} selected: ${selectedKeys.join(', ') || 'none'}`));
  log('Rows with a score under 60 are locked and cannot be ticked.');
  return () => off();
}
export const actions = {
  keys: (api) => api.selectRows([2, 4, 7]),
  add: (api) => api.selectRows([3, 5], { add: true }),
  where: (api) => {
    const count = api.selectWhere({ team: 'Dev' });
    say(`Selected ${count} selectable rows in team Dev (locked rows are skipped).`);
  },
  locked: (api) => {
    const locked = api.findRows((row) => row.score < 60)[0];
    if (locked === undefined)
      return;
    try {
      api.selectRows([locked.id]);
    }
    catch (error) {
      say(`A locked row cannot be selected with selectRows: ${error.message}`);
    }
  },
  remove: (api) => api.deselectRows([2]),
  read: (api) => {
    const rows = api.getSelectedRows();
    say(`getSelectedRows: ${rows.map((r) => r.name).join(', ') || 'none'} / row 4 selected: ${String(api.isSelected(4))}`);
  },
  clear: (api) => api.deselectAllRows(),
};