# Selection

> Let users select one or many rows, add a checkbox column, and drive selection from code with stable row IDs.

Row selection is off by default. Turn it on with `rowSelection`, optionally add a checkbox column with `checkboxSelection`, and listen to `selectionChanged`.

```ts title="dispatch-grid.ts"
import { createGrid, type ColumnDef } from '@birchui/core';

interface WorkOrder {
  id: string;
  site: string;
  technician: string;
  scheduled: string;
  status: 'Open' | 'Assigned' | 'Done';
}

const columns: ColumnDef<WorkOrder>[] = [
  { field: 'id', header: 'Work order', width: 130 },
  { field: 'site', flex: 1 },
  { field: 'technician' },
  { field: 'scheduled', type: 'date' },
  { field: 'status' },
];

const grid = createGrid<WorkOrder>(document.querySelector('#work-orders')!, {
  columns,
  rows: workOrders,
  getRowId: (w) => w.id,
  rowSelection: 'multiple',
  checkboxSelection: true,
});

const assignButton = document.querySelector<HTMLButtonElement>('#assign')!;

grid.on('selectionChanged', ({ selected }) => {
  assignButton.disabled = selected.length === 0;
  assignButton.textContent = selected.length ? `Assign ${selected.length} work orders` : 'Assign';
});
```

## Selection modes

| `rowSelection` | Behaviour |
| --- | --- |
| `false` (default) | Rows cannot be selected. Clicking a cell only focuses it. |
| `'single'` | Clicking a row selects it and deselects any other row. |
| `'multiple'` | Clicking a row selects only that row. <kbd>Ctrl</kbd>+click or <kbd>Cmd</kbd>+click toggles a row while keeping the others. <kbd>Shift</kbd>+click selects the range from the last clicked row; add <kbd>Ctrl</kbd> or <kbd>Cmd</kbd> to add the range to the existing selection. |

Clicks on buttons, links and form controls inside cells never change the selection, so action buttons in a [cell renderer](https://docs.birchui.com/grid/columns.md#cell-renderers-cell) work as expected.

With the keyboard:

| Key | Action |
| --- | --- |
| <kbd>Space</kbd> | Toggle the focused row |
| <kbd>Shift</kbd>+<kbd>Space</kbd> | Select the range from the last toggled row to the focused row (`'multiple'`) |
| <kbd>Ctrl</kbd>+<kbd>A</kbd> or <kbd>Cmd</kbd>+<kbd>A</kbd> | Select all rows (`'multiple'`) |

The grid root reports `aria-multiselectable="true"` in `'multiple'` mode, and every row reports `aria-selected`. See [Keyboard navigation & accessibility](https://docs.birchui.com/grid/accessibility.md).

## Checkbox column

`checkboxSelection: true` adds a 44-pixel checkbox column pinned to the left, with the ID `__select`. It is only added when `rowSelection` is set.

- Clicking a checkbox toggles that row without affecting the others. <kbd>Shift</kbd>+click selects a range.
- In `'multiple'` mode the header has a select-all checkbox. It selects every data row that passes the current filters, across all pages, and shows an indeterminate state when only some of them are selected. In `'single'` mode it is hidden.
- With a checkbox column, clicking elsewhere in a row focuses the cell but does not change the selection. Users select with the checkboxes only, which avoids accidental deselection on screens where people also edit cells.

The checkbox column is generated by the grid: it is not part of `columns`, cannot be edited, sorted, filtered, resized or moved, is excluded from the quick filter and CSV export, and is reported with `generated: true` by `getColumns()`.

## Reading the selection

```ts
const rows = grid.getSelectedRows();
const ids = grid.getSelectedIds();
```

`getSelectedRows()` returns your row objects. `getSelectedIds()` returns their IDs, which is what you usually send to a server.

## Changing the selection from code

```ts
grid.setRowSelected('WO-2291', true);
grid.setRowSelected('WO-2288', false);
grid.selectAll();
grid.deselectAll();
```

All of these fire `selectionChanged` when the selection actually changes. `selectAll()` selects every data row that passes the current filters, on every page, and does nothing in `'single'` mode. In `'single'` mode, `setRowSelected(id, true)` replaces the current selection. To restore a saved selection after loading data:

```ts
const saved: string[] = JSON.parse(sessionStorage.getItem('dispatch.selection') ?? '[]');
grid.setRows(await fetchWorkOrders());
for (const id of saved) grid.setRowSelected(id, true);

grid.on('selectionChanged', () => {
  sessionStorage.setItem('dispatch.selection', JSON.stringify(grid.getSelectedIds()));
});
```

**`GridApi`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface GridApi<TRow = RowData> extends Widget<GridOptions<TRow>, GridEvents<TRow>>, GridFeatureApi<TRow>
```

| Property | Type | Description |
| --- | --- | --- |
| `getSelectedRows` | `() => TRow[]` |  |
| `getSelectedIds` | `() => string[]` |  |
| `setRowSelected` | `(id: string, selected: boolean) => void` |  |
| `selectAll` | `() => void` |  |
| `deselectAll` | `() => void` |  |

## Selection and data changes

Selection is stored by row ID, which is why `getRowId` matters:

- With `getRowId`, a selected row stays selected after `setRows()` or `applyTransaction({ update })` replaces its object, as long as the ID is still present.
- Rows removed with `applyTransaction({ remove })`, and rows missing from new data passed to `setRows()` or `update({ rows })`, leave the selection. The grid fires `selectionChanged` when that removes any selected row, so a toolbar bound to the selection stays correct after a refresh.
- Filtering hides rows but does not deselect them. `getSelectedRows()` still includes selected rows that are filtered out.

## Styling selected rows

Selected rows get the `lq-row-selected` class and the `--lq-selection-bg` background. Override the property on the grid element itself:

```css
#work-orders .lq-grid {
  --lq-selection-bg: rgba(26, 127, 55, 0.14);
}
```

## Acting on clicks without selecting

To open a record on click instead of selecting it, keep `rowSelection: false` and listen to `rowClick` or `cellClick`:

```ts
grid.on('rowClick', ({ row, event }) => {
  if (!row) return;
  if (event.metaKey || event.ctrlKey) window.open(`/work-orders/${row.id}`, '_blank');
  else router.navigate(`/work-orders/${row.id}`);
});
```

## Related

- [Range selection](https://docs.birchui.com/grid-pro/range-selection.md) selects rectangular cell ranges in Grid Pro.
- [CSV export](https://docs.birchui.com/grid/csv-export.md) can export only the selected rows.
