← Examples

Custom serializer & deserializer

By default the hidden input value is a comma-separated list of tag values, and initial parsing splits on commas. A custom serialize function lets you change the format, and the paired deserialize reads the original input's value back into tags — together they let a non-comma format round-trip through a form submit and server re-render. This example uses JSON with label and value fields and pre-populates from a JSON-encoded initial value.

Hidden input value

View code
<label for="tags">Select tools</label>
<input id="tags" type="text" name="tools"
       value='[{"label":"Vite","value":"vite"},{"label":"VS Code","value":"vscode"}]' />

<pre id="value-output">—</pre>

<script type="module">
  import { Taga11y } from '../dist/taga11y.mjs';

  const input = document.getElementById('tags');
  const valueOutput = document.getElementById('value-output');

  const taga = new Taga11y(input, {
    suggestions: [
      { label: 'ESLint', value: 'eslint' },
      { label: 'Git', value: 'git' },
      { label: 'Vite', value: 'vite' },
      { label: 'VS Code', value: 'vscode' },
    ],
    // Each TagData also carries an internal `id` (e.g. "taga11y-tags-tag-0"); you can
    // include it in the serialized payload if your consumer needs it. Note that ids
    // are regenerated on every init, so they will not round-trip through deserialize.
    serialize: (tags) => JSON.stringify(
      tags.map((t) => ({ id: t.id, label: t.label, value: t.value })),
      null,
      2,
    ),
    // Input side: parse the same JSON back into SuggestionItem[]
    deserialize: (raw) => (raw ? JSON.parse(raw) : []),
  });

  function updateOutput() {
    valueOutput.textContent = taga._dom?.hiddenInput?.value ?? '—';
  }

  taga.on('taga11y:change', updateOutput);
  updateOutput();

  // Switch to default (comma-join, both directions)
  taga.settings({
    serialize: (tags) => tags.map((t) => t.value).join(','),
    deserialize: (raw) => (raw ? raw.split(',').map((v) => v.trim()).filter(Boolean) : []),
  });

  // Switch back to JSON (both directions)
  taga.settings({
    serialize: (tags) => JSON.stringify(
      tags.map((t) => ({ id: t.id, label: t.label, value: t.value })),
      null,
      2,
    ),
    deserialize: (raw) => (raw ? JSON.parse(raw) : []),
  });
</script>