Advanced reference · 2.3

Advanced options, HTML and JavaScript.

The demo shows every control; this page shows how to wire the parts that need more than a visual check: build loading, option precedence, remote paging, Promise validation, upload handlers, events and teardown. Every example has an HTML and a JavaScript version where both are possible.

Technical

Build and load order

Load exactly one build per page. Structure and theme are separate files, and plugin-core.css must come before plugin-theme.css. Your own overrides go after both.

BuildJavaScriptCSSUse when
Full zidan-form.js
224 kB raw · 131 kB min
plugin-core.css 40 → 31 kB
plugin-theme.css 47 → 39 kB
Several control families on one page.
Select-only dist/select/zidan-select.js
114 kB raw · 68 kB min
plugin-select-core.css 12 → 9 kB
plugin-select-theme.css 32 → 27 kB
Only select, combobox or tags.
File-only dist/file/zidan-file.js
86 kB raw · 50 kB min
plugin-file-core.css 10 → 7 kB
plugin-file-theme.css 34 → 29 kB
Only file uploads.

Sizes are measured from the 2.4.2 build (1 kB = 1,024 bytes; CSS shows readable → minified). Minified files ship in the npm package and are generated by npm run build.

<link rel="stylesheet" href="plugin-core.css">
<link rel="stylesheet" href="plugin-theme.css">
<script src="zidan-form.js"></script>

<!-- select-only or file-only pages: use that build's JS and both
     matching CSS files instead of the full bundle — never both. -->
ConstraintDetail
RuntimeNo dependencies. Browser APIs only; classic script, ESM wrapper and plain CSS.
Build stepNone for consumers. Node 18+ is only needed for this repository's tests and dist/ build.
Auto-init[data-zidan-select], [data-zidan], .zidan-select, .zidan-field, zidan-form wrappers and configured targets, on DOMContentLoaded.
Opt out<html data-zidan-auto-init="false"> or window.ZIDAN_SELECT_CONFIG = { autoInit: false } before the script.
Native stateThe real control stays in the DOM at 1×1 px (never display:none), so FormData, reset(), :invalid and input.files keep working.

Pick your script

Which build, which JavaScript function

Each build exposes only the functions for the controls it ships. Load one build and copy the block below that matches it — the three snippets are not interchangeable, and a function that belongs to another build is simply undefined.

You loadedFunctions available on windowNot in this build
Full bundle
zidan-form.js
initZidanForms · initZidanSelects · zidanField · zidanSelect · ZidanForm · ZidanSelect · registerZidanIcon —
Select-only
dist/select/zidan-select.js
initZidanSelects · zidanSelect · ZidanForm · ZidanSelect · registerZidanIcon initZidanForms · zidanField
File-only
dist/file/zidan-file.js
initZidanForms · zidanField · ZidanForm · registerZidanIcon initZidanSelects · zidanSelect · ZidanSelect

Full bundle — selects, inputs, checkboxes, radios and files

<script src="zidan-form.js"></script>
<script>
  // every [data-zidan] / [data-zidan-select] control on the page
  initZidanForms(document);

  // or initialise one control at a time
  zidanField('#phone', { phone: { country: 'GB', format: 'international' } });
  zidanSelect('#country', { mode: 'combobox', clearable: true });
</script>

Select-only — dropdowns, combobox and tags only

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/zidan-select@2.4.2/dist/select/plugin-select-core.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/zidan-select@2.4.2/dist/select/plugin-select-theme.css">
<script src="https://cdn.jsdelivr.net/npm/zidan-select@2.4.2/dist/select/zidan-select.js"></script>
<script>
  initZidanSelects(document);
  zidanSelect('#country', { mode: 'combobox' });

  // zidanField() and initZidanForms() do not exist in this build;
  // ZidanForm.field() returns [] because no input or file family is loaded.
</script>

File-only — uploads only

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/zidan-select@2.4.2/dist/file/plugin-file-core.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/zidan-select@2.4.2/dist/file/plugin-file-theme.css">
<script src="https://cdn.jsdelivr.net/npm/zidan-select@2.4.2/dist/file/zidan-file.js"></script>
<script>
  initZidanForms(document);
  zidanField('#files', { variant: 'dropzone', maxFiles: 4 });

  // zidanSelect() and initZidanSelects() do not exist in this build.
</script>

Same markup in all three builds. Auto-init reads the same data-zidan / data-zidan-select attributes, and ZidanForm exists everywhere for refresh(), destroyAll() and observe(). The examples further down this page assume the full bundle unless they say otherwise.

Entry points

Initialization: markup, selectors or config

Markup is enough for most fields. Use the API when you need callbacks, render hooks, remote data or an option that cannot be written as an attribute.

<form class="zidan-form">
  <select name="country" data-zidan-select="combobox"
          data-zidan-label="Country" data-zidan-clearable="true">…</select>

  <input type="file" name="docs" data-zidan="file"
         data-zidan-file-variant="dropzone" data-zidan-max-size-mb="4">

  <input type="email" name="email" data-zidan="input"
         data-zidan-label="Email" data-zidan-auto-icon="true">

  <fieldset data-zidan="radio-group" data-zidan-variant="tile">…</fieldset>
</form>

<script src="zidan-form.js"></script>
<script>
  initZidanForms(document);   // fields
  initZidanSelects(document); // selects, if you prefer explicit init
</script>
Entry pointReturnsNotes
zidanSelect(target, opts)Instance or arrayAccepts a selector, element or NodeList. Plain selects are not touched by auto-init.
zidanField(target, opts)Field or arrayWorks on marked controls and on plain supported <input>/<textarea> elements.
initZidanSelects(scope?, opts?)Select[]Scans the scope for marked selects and configured targets.
initZidanForms(scope?, opts?)Field[]Scans for marked fields and zidan-form wrappers.
ZidanForm.init(scope, opts)Field[]Shared options are merged into every field.
ZidanForm.get(input)Field | nullLook up the instance attached to a native control.
ZidanForm.refresh(scope?)Field[]Re-scan and re-sync native state without rebuilding the page.
ZidanForm.destroyAll()voidRestores every enhanced control, including those in subsets.

Debugging

Option precedence and the HTML/JS boundary

When the same option is set twice, the more specific source wins. Functions can only be passed from JavaScript, which is why async fetching, render hooks and custom validators have no data-attribute equivalent.

PrioritySourceExample
1 — highestJavaScript optionszidanSelect('#x', { maxTags: 3 })
2data-zidan-options JSONdata-zidan-options='{"maxTags":3}'
3Individual data attributesdata-zidan-max-tags="4"
4 — lowestNative markup and plugin defaultsmultiple, required, maxlength

Counter detail: maxlength only supplies the default counter limit. data-zidan-counter (or the counter JS option) overrides it.

<select id="skills" class="zidan-select" multiple
        data-zidan-options='{"mode":"tags","maxTags":4,"placeholder":"Type and press Enter"}'>
  <option>Design</option>
  <option>Frontend</option>
</select>

Select

Remote paging, caching and tags

A paged fetchOptions returns { items, hasMore }. Pages are cached per query, the footer shows a load-more button, and scrolling near the bottom fetches the next page automatically.

const picker = zidanSelect('#owner', {
  mode: 'combobox',
  fetchPageSize: 20,
  autoLoadMore: true,
  cacheResults: true,
  fetchOptions: async (query, signal, { page, pageSize }) => {
    const res = await fetch('/api/users?q=' + encodeURIComponent(query)
      + '&page=' + page + '&size=' + pageSize, { signal });
    const data = await res.json();
    return {
      items: data.rows.map(u => ({ value: u.id, label: u.name })),
      hasMore: data.page + 1 < data.pages
    };
  },
  onLoadMore: ({ page }) => console.log('page', page)
});

picker.loadMore();          // fetch the next page manually
picker.hasMoreResults();    // boolean
picker.getAsyncState();     // { query, page, hasMore, loading, fetchingMore, error }
picker.refreshOptions();    // clear cache and refetch page 0
picker.clearCache();        // drop cached pages only

Live: paged remote select

Loaded from an in-memory paged source.

Open the list, scroll, or use Load more.

Remote results are not filtered again on the client. Keep values stable across pages so the merge can de-duplicate them. The cache limit is ZidanSelect.cacheLimit = 50 pages, least-recently-used.

Tags & render hooks

zidanSelect('#skills', {
  mode: 'tags',
  maxTags: 4,
  minTagLength: 2,
  allowFreeText: true,
  commitOnTab: true,
  validateTag: tag => tag.length <= 16 || 'Keep tags short',
  renderTag: tag => '<span>' + tag + '</span>'
});

Methods worth knowing

  • getValue() / setValue(v) / clear()
  • setOptions(items) rebuilds native options
  • loadMore(), clearCache(), refreshOptions()
  • hasMoreResults(), getAsyncState()
  • addTag(), removeTag(), getTags()
  • setLayout(), setFramework(), setScrollbar()
  • setValidation(), refresh(), destroy()

Fields

Promise validation, phone, date and range

validate and validateDate may return a Promise. The field shows a pending state, writes the pending message into native validity so submission waits, aborts the previous request when the value changes and ignores stale resolutions.

<!-- Static rules work as attributes -->
<input type="tel" data-zidan="input" data-zidan-label="Phone"
       data-zidan-phone="true" data-zidan-phone-country="GB"
       data-zidan-phone-format="international">

<input type="date" data-zidan="input" data-zidan-label="Delivery"
       data-zidan-disable-weekends="true"
       data-zidan-disabled-dates="2026-12-25,2027-01-01">

<input type="range" min="0" max="1000" step="50" value="400"
       data-zidan="input" data-zidan-range-variant="minimal"
       data-zidan-range-bubble="true" data-zidan-output="#adv-range-out">

<input type="range" min="0" max="30" value="5"
       data-zidan="input" data-zidan-range-bubble-mode="active"
       data-zidan-range-bubble-position="bottom" data-zidan-range-fill="false"
       data-zidan-range-min-label="Low" data-zidan-range-max-label="High"
       data-zidan-range-ticks="10,20">

Live: async email check

Try taken@example.com.

Live: phone formatting

Typing reformats around the caret; a country selector is optional.

Live: range ticks + formatter

Output: €400. Labeled endpoint ticks replace the min/max scale, so 0 and 1,000 appear once.

Live: range chrome

Bubble on hover / focus / drag below the track, no progress fill, marks at 10 and 20, custom scale ends.

When pending, the native control carries the pending message, so form.checkValidity() and submit handlers wait. destroy() aborts in-flight checks; field.reset() clears the pending state. Listen for zidan:async-validation with { valid, message }.

Files

Upload pipeline: handlers, progress and retries

Native input.files stays the source of truth. Removing a file rebuilds it with DataTransfer. For real uploads use an XHR endpoint or a custom upload() handler; for demos use simulateUpload.

zidanField('#files', {
  variant: 'dropzone',
  maxFiles: 4,
  maxSizeMB: 5,
  upload(file, context) {
    // context: { file, field, formData, signal, onProgress, complete, fail }
    fetch('/upload', {
      method: 'POST',
      body: context.formData,
      signal: context.signal
    })
      .then(res => res.ok ? res.json() : Promise.reject(res.status))
      .then(context.complete)
      .catch(context.fail);
  },
  renderFile(itemEl, { index }) {
    itemEl.dataset.index = index;
  }
});

// Or let the plugin send multipart XHR:
// zidanField('#files', { uploadUrl: '/api/files', uploadField: 'file' });

Live: compact upload with simulated progress

Max 2 files · 2 MB each

Methods: getFiles(), addFiles(), replaceFiles(), removeFile(), uploadAll(), uploadFile(), cancelUpload(), cancelAll(), retryUpload(), getUploadState(). Events: zidan:upload-start, -progress, -success, -error, -cancel.

Integration

Events and lifecycle

Events bubble from the enhanced wrapper, so one document-level listener can cover a whole form. Every listener, DOM node and in-flight request is removed by destroy().

EventDetail
zidan:change{ instance, kind, value }, { checked } or { files }
zidan:validation{ instance, state, message? }
zidan:async-validation{ valid, message } when a Promise rule settles
zidan:load-more{ page, query } for appended remote pages
zidan:step{ instance, value, direction }
zidan:phone-country / zidan:phone-format{ country } / { format }
zidan:icon-click / zidan:pickerIcon action or date/time picker request
zidan:upload-*File state, name, progress, result or message
zidan:remove / zidan:clearFile removal and field clearing
zidan:init / zidan:destroy / zidan:errorLifecycle and caught callback/upload errors
document.addEventListener('zidan:change', event => {
  console.log(event.detail.kind, event.detail.value || event.detail.checked);
});

document.addEventListener('zidan:upload-progress', event => {
  console.log(event.detail.name, event.detail.progress + '%');
});

const observer = ZidanForm.observe(document.body); // adds/removes nodes
// teardown
observer.disconnect();
ZidanForm.destroyAll();

// Per instance
field.update();      // mirror native disabled/required/value
field.refresh();     // re-render without rebuilding
field.destroy();     // restore original markup + listeners

The observer reacts to nodes added or removed inside the observed root. If you remove the container itself, call field.destroy() or ZidanForm.destroyAll() first.

Platform

Themes, RTL, adapters and TypeScript

Structure never carries colour. Override tokens in the theme layer or register your own theme name; layouts and framework adapters resolve per element, then ancestor, then <html>.

Theme tokens

.my-brand {
  --zs-primary: #e11d48;
  --zs-primary-soft: #fff1f4;
  --zs-focus-ring: rgba(225, 29, 72, .22);
  --zs-radius: 14px;
  --zs-check-checked-bg: #e11d48;
}

/* register a name before fields initialise:
   ZidanForm.themes.push('brand'); */

Framework adapters

SettingValues
data-zs-frameworkbootstrap · tailwind · bulma · foundation
data-zidan-frameworkPer field; wins over the ancestor
Themedefault · modern · minimal · dark · glass
LayoutsSelect: 5 skins. Fields: stacked · inline · compact · floating · outlined · card
Grid.zs-form-grid auto-fit container; .zs-full spans a row

RTL uses logical properties

The wrapper follows dir; transforms for arrows, ticks and icons are mirrored.

TypeScript declarations

import ZidanForm, { zidanField } from 'zidan-select';

const field = zidanField('#email', {
  validate: async value => value.includes('@') || 'Enter an email'
});

ZidanForm.themes.push('brand');

Declarations ship for the full package and for zidan-select/select and zidan-select/file.

TopicDetail
BrowsersChromium 105+, Firefox 121+, Safari 15.4+ / iOS 15.4+. Firefox exposes thin native scrollbars only.
Validation librariesNative HTML5, jQuery Validation, JustValidate and Parsley. Native controls stay measurable; aria-invalid and .zs-field--invalid stay in sync.
FrameworksInitialise after mount, call destroy() before unmount. Guides for React, Next.js App Router, Vue 3 and Angular ship in docs/frameworks.md.
CSSplugin-core.css is structural only — no colour literals. Put your tokens or theme after plugin-theme.css.