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.
- No runtime dependencies
- Classic script + ESM
- HTML attrs, JSON attrs or JS options
- Async rules abort on change
- Full, select-only and file-only builds
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.
| Build | JavaScript | CSS | Use when |
|---|---|---|---|
| Full | zidan-form.js224 kB raw · 131 kB min |
plugin-core.css 40 → 31 kBplugin-theme.css 47 → 39 kB |
Several control families on one page. |
| Select-only | dist/select/zidan-select.js114 kB raw · 68 kB min |
plugin-select-core.css 12 → 9 kBplugin-select-theme.css 32 → 27 kB |
Only select, combobox or tags. |
| File-only | dist/file/zidan-file.js86 kB raw · 50 kB min |
plugin-file-core.css 10 → 7 kBplugin-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. -->
// ESM
import ZidanForm, { initZidanForms, initZidanSelects, zidanField } from 'zidan-select';
import 'zidan-select/css/core';
import 'zidan-select/css/theme';
// CommonJS
const { ZidanForm, initZidanForms, initZidanSelects } = require('zidan-select');
// One page = one build. Subsets are complete, not add-ons:
// import { ZidanSelect } from 'zidan-select/select';
// import 'zidan-select/select/css/core';
// import 'zidan-select/select/css/theme';
| Constraint | Detail |
|---|---|
| Runtime | No dependencies. Browser APIs only; classic script, ESM wrapper and plain CSS. |
| Build step | None 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 state | The 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 loaded | Functions available on window | Not in this build |
|---|---|---|
Full bundlezidan-form.js |
initZidanForms · initZidanSelects · zidanField · zidanSelect · ZidanForm · ZidanSelect · registerZidanIcon |
— |
Select-onlydist/select/zidan-select.js |
initZidanSelects · zidanSelect · ZidanForm · ZidanSelect · registerZidanIcon |
initZidanForms · zidanField |
File-onlydist/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>
// One select, one field, or every match
const picker = zidanSelect('#country', { mode: 'combobox', clearable: true });
const upload = zidanField('#docs', { variant: 'dropzone', maxSizeMB: 4 });
const fields = initZidanForms(document);
// Explicit targets before the generic scan; its options win
window.ZIDAN_FORM_CONFIG = {
targets: [
'#country',
{ selector: '#brands', options: { mode: 'tags', maxTags: 3 } }
],
fieldTargets: [
{ selector: '#email', options: { icon: 'mail' } }
],
formTargets: ['#checkout']
};
// Later, after dynamic DOM changes
const observer = ZidanForm.observe(document.body);
ZidanForm.refresh(document);
observer.disconnect();
| Entry point | Returns | Notes |
|---|---|---|
zidanSelect(target, opts) | Instance or array | Accepts a selector, element or NodeList. Plain selects are not touched by auto-init. |
zidanField(target, opts) | Field or array | Works 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 | null | Look 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() | void | Restores 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.
| Priority | Source | Example |
|---|---|---|
| 1 — highest | JavaScript options | zidanSelect('#x', { maxTags: 3 }) |
| 2 | data-zidan-options JSON | data-zidan-options='{"maxTags":3}' |
| 3 | Individual data attributes | data-zidan-max-tags="4" |
| 4 — lowest | Native markup and plugin defaults | multiple, 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>
// JS options beat the JSON attribute, which beats data-* attributes
zidanSelect('#skills', {
mode: 'tags',
maxTags: 2,
validateTag: tag => tag.length <= 12 || 'Use 12 characters or fewer'
});
// Functions cannot come from HTML or JSON:
// fetchOptions, renderOption, renderSelected, renderTag, formatTag,
// validateTag, validate, validateDate, upload, callbacks, customClasses
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 optionsloadMore(),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">
const email = zidanField('#email', {
alwaysValidate: true,
showValidState: true,
messages: { pending: 'Checking…', generic: 'That email is not available.' },
validate: async (value, field, { signal }) => {
if (!value) return true;
const res = await fetch('/api/check-email?e=' + encodeURIComponent(value), { signal });
const { taken } = await res.json();
return taken ? 'This email is already registered.' : true;
}
});
await email.validate(); // Promise<boolean>
email.isPending(); // true while the request is in flight
email.checkAsync(); // run the async rule without changing focus
email.setError('…'); // manual message
email.clearError();
// Range chrome: same options as data attributes, plus array tick values
zidanField('#adv-range-chrome', {
rangeTicks: [10, 20], // or '10,20' from the data attribute
rangeBubbleMode: 'active', // 'always' | 'active' | 'never'
rangeBubblePosition: 'bottom', // 'top' | 'bottom'
rangeFill: false, // progress fill off
rangeMinLabel: 'Low',
rangeMaxLabel: 'High',
rangeFormat: value => value + ' days'
});
Live: async email check
Trytaken@example.com.
Live: phone formatting
Typing reformats around the caret; a country selector is optional.
Live: range ticks + formatter
Output: . 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' });
<input type="file" id="files" name="files" multiple
accept="image/*,.pdf"
data-zidan="file"
data-zidan-file-variant="dropzone"
data-zidan-max-files="4"
data-zidan-max-size-mb="5"
data-zidan-upload-url="/api/files"
data-zidan-upload-field="file">
<!-- demo only: no network, animated progress -->
<input type="file" data-zidan="file"
data-zidan-simulate-upload="true"
data-zidan-simulate-duration="1400">
Live: compact upload with simulated progress
Max 2 files · 2 MB eachMethods: 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().
| Event | Detail |
|---|---|
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:picker | Icon action or date/time picker request |
zidan:upload-* | File state, name, progress, result or message |
zidan:remove / zidan:clear | File removal and field clearing |
zidan:init / zidan:destroy / zidan:error | Lifecycle 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
| Setting | Values |
|---|---|
data-zs-framework | bootstrap · tailwind · bulma · foundation |
data-zidan-framework | Per field; wins over the ancestor |
| Theme | default · modern · minimal · dark · glass |
| Layouts | Select: 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.
| Topic | Detail |
|---|---|
| Browsers | Chromium 105+, Firefox 121+, Safari 15.4+ / iOS 15.4+. Firefox exposes thin native scrollbars only. |
| Validation libraries | Native HTML5, jQuery Validation, JustValidate and Parsley. Native controls stay measurable; aria-invalid and .zs-field--invalid stay in sync. |
| Frameworks | Initialise after mount, call destroy() before unmount. Guides for React, Next.js App Router, Vue 3 and Angular ship in docs/frameworks.md. |
| CSS | plugin-core.css is structural only — no colour literals. Put your tokens or theme after plugin-theme.css. |