JavaScript Form & Select Enhancement Library – ZidanForm

Category: Form , Javascript | November 25, 2026
Authorakhtar1985
Last UpdateNovember 25, 2026
LicenseMIT
Views0 views
JavaScript Form & Select Enhancement Library – ZidanForm

ZidanForm is a dependency-free JavaScript library for styling and enhancing native form controls, from searchable select dropdowns to file uploads and radio/checkbox inputs.

It preserves native form values and validation, and offers dedicated select-only and file-only builds for pages that do not need the full set of controls.

Features

  • Searchable dropdowns, comboboxes, multiple selections, and tag inputs.
  • Remote option loading with pagination, caching, and request cancellation.
  • Checkboxes, switches, radio groups, and multiple field layouts.
  • Drag-and-drop file selection, previews, upload progress, cancellation, and retry.
  • Input icons, clear buttons, number steppers, and phone formatting.
  • Range sliders, native date/time picker buttons, and date restrictions.
  • Native FormData, form.reset(), and constraint-validation support.
  • Five theme presets, CSS variables, RTL support, and framework styling adapters.
  • Async custom validation and typed ESM entry points.

How To Use It

Choose the right build

Controls neededFiles in the package
Full formzidan-form.js, plugin-core.css, plugin-theme.css.
Select-onlydist/select/zidan-select.js, dist/select/plugin-select-core.css, dist/select/plugin-select-theme.css.
File-onlydist/file/zidan-file.js, dist/file/plugin-file-core.css, dist/file/plugin-file-theme.css.

Basic Usage

Load core CSS before theme CSS. The full browser build initializes marked controls after the DOM is ready.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/plugin-core.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/plugin-theme.css">
<form id="account-form">
  <label for="country">Country</label>
  <select id="country" name="country" required
          data-zidan-select="combobox" data-zidan-searchable="true">
    <option value="">Choose a country</option>
    <option value="fr">France</option>
    <option value="jp">Japan</option>
    <option value="us">United States</option>
  </select>
  <label for="updates">
    <input id="updates" type="checkbox" name="updates" value="yes"
           data-zidan="checkbox" data-zidan-variant="switch">
    Email updates
  </label>
  <fieldset data-zidan="radio-group" data-zidan-variant="inline">
    <legend>Account type</legend>
    <label><input type="radio" name="account" value="personal" checked> Personal</label>
    <label><input type="radio" name="account" value="business"> Business</label>
  </fieldset>
  <label for="avatar">Profile image</label>
  <input id="avatar" type="file" name="avatar" accept="image/*"
         data-zidan="file" data-zidan-variant="avatar">
  <button type="submit">Save</button>
  <button type="reset">Reset</button>
</form>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/zidan-form.js"></script>

Enhance number, phone, and range inputs

The full build also accepts data-zidan="input" on number, telephone, date/time, range, and text controls.

<label for="quantity">Quantity</label>
<input id="quantity" type="number" name="quantity" value="1" min="1" max="10"
       data-zidan="input" data-zidan-stepper="split">
<label for="mobile">Phone</label>
<input id="mobile" type="tel" name="mobile" data-zidan="input"
       data-zidan-phone="true" data-zidan-phone-country="US"
       data-zidan-phone-format="international">
<label for="amount">Amount</label>
<input id="amount" type="range" name="amount" min="0" max="100" value="50"
       data-zidan="input" data-zidan-range-variant="stepped"
       data-zidan-range-ticks="0,25,50,75,100"
       data-zidan-range-tick-labels="true" data-zidan-output="#amount-value">
<output id="amount-value" for="amount"></output>

Use a smaller browser bundle

For a page with only a select, use the select-only build. Keep the native <select> and initialize it by selector, ID, or element.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/select/plugin-select-core.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/select/plugin-select-theme.css">
<select id="team" name="team">
  <option value="design">Design</option>
  <option value="engineering">Engineering</option>
  <option value="support">Support</option>
</select>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/select/zidan-select.js"></script>
<script>
  const teamPicker = zidanSelect('#team', {
    mode: 'combobox',
    searchable: true,
    clearable: true
  });
</script>

For file inputs only, replace these three files with dist/file/plugin-file-core.css, dist/file/plugin-file-theme.css, and dist/file/zidan-file.js. Initialize a file input with zidanField().

Install with npm

npm install zidan-select
import ZidanForm, { initZidanForms, initZidanSelects, zidanField } from 'zidan-select';
import 'zidan-select/css/core';
import 'zidan-select/css/theme';
initZidanSelects(document);
initZidanForms(document);

For a smaller module, import from zidan-select/select or zidan-select/file and use the corresponding /css/core and /css/theme exports.

Initialize existing controls with JavaScript

Use zidanSelect() for a plain select that has no Zidan attributes. The function accepts a selector, element, or NodeList.

<select id="products" name="product">
  <option value="sku-42">Keyboard</option>
  <option value="sku-43">Mouse</option>
</select>
const picker = zidanSelect('#products', {
  mode: 'combobox',
  label: 'Product',
  placeholder: 'Search products',
  searchable: true,
  clearable: true
});
picker.getValue();
picker.setValue('sku-42');
picker.setOptions([
  { value: 'sku-42', label: 'Keyboard' },
  { value: 'sku-43', label: 'Mouse', group: 'Accessories' }
]);

Configure controls in HTML

Add data-zidan-options as JSON or use zidan-select, zidan-field, and zidan-form marker classes. For automatic selector targeting, assign window.ZIDAN_FORM_CONFIG before loading the library.

data-zidan-options accepts JSON values. Define callbacks, custom upload handlers, and SVG markup in JavaScript. An explicit target option takes precedence over JSON options, followed by individual data attributes and defaults.

<select class="zidan-select" name="skills" multiple
        data-zidan-options='{"mode":"tags","maxTags":3,"placeholder":"Add skills"}'>
  <option value="css">CSS</option>
  <option value="js">JavaScript</option>
</select>
<script>
  window.ZIDAN_FORM_CONFIG = {
    targets: ['#department'],
    fieldTargets: [{ selector: '#photo', options: { variant: 'gallery' } }],
    formTargets: ['#registration']
  };
</script>
<script src="https://cdn.jsdelivr.net/npm/zidan-select/zidan-form.js"></script>

Load select options from an API

The remote endpoint must return items you can map to { value, label }. Supply fetchPageSize and return { items, hasMore } for paginated results. The callback receives an AbortSignal and paging context.

For a declarative endpoint, set data-zidan-fetch-url plus optional query, page-size, item-path, and total-path attributes on the native select.

<select id="customer" name="customer"></select>
const customers = zidanSelect('#customer', {
  mode: 'combobox',
  fetchPageSize: 20,
  fetchOptions: async (query, signal, { page, pageSize }) => {
    const params = new URLSearchParams({
      q: query,
      page: String(page),
      limit: String(pageSize)
    });
    const response = await fetch('/api/customers?' + params, { signal });
    if (!response.ok) throw new Error('Unable to load customers');
    const data = await response.json();
    return {
      items: data.items.map(item => ({ value: item.id, label: item.name })),
      hasMore: data.hasMore
    };
  }
});

Add upload progress to a file input

Set uploadUrl to a server endpoint that accepts multipart POST requests. ZidanForm handles the picker, progress UI, cancellation, and retry; the server must process and store uploaded files.

simulateUpload: true previews the upload UI locally and sends no files to the server. To use your own transport, supply upload(file, context) and report progress through context.onProgress(); finish with a resolved Promise or context.complete().

<input type="file" id="attachments" name="attachments" multiple>
const uploads = zidanField('#attachments', {
  variant: 'dropzone',
  accept: 'image/*,.pdf',
  maxFiles: 4,
  maxSizeMB: 5,
  uploadUrl: '/api/uploads',
  onUploadProgress: ({ name, progress }) => {
    console.log(name, progress);
  }
});
uploads.getUploadState();

Validate a field asynchronously

An async validator receives { signal, field, instance } as its third argument. A pending check sets the native validity state until it finishes; the previous request is aborted if the input changes.

<input type="email" id="email" name="email" required>
const emailField = zidanField('#email', {
  alwaysValidate: true,
  showValidState: true,
  validate: async (value, field, { signal }) => {
    if (!value) return true;
    const response = await fetch(
      '/api/check-email?value=' + encodeURIComponent(value),
      { signal }
    );
    if (!response.ok) throw new Error('Validation is unavailable');
    const result = await response.json();
    return result.taken ? 'Email address is already in use.' : true;
  }
});
emailField.validate().then((valid) => console.log(valid));

Configuration Reference

Field options work with checkbox, radio, file, text, and other native inputs. Select options apply to ZidanSelect instances. Values that depend on the native input use the corresponding native attribute as their default.

Shared field options

Option / APIDescription
variantControl skin. Default default for checkboxes; file and radio groups have their own variants. Attribute: data-zidan-variant.
layoutField layout, default stacked: stacked, inline, compact, floating, outlined, card. data-zidan-layout.
themeTheme preset, default default: default, modern, minimal, dark, glass. data-zidan-theme/data-zs-theme.
frameworkCSS framework adapter, default none: none, bootstrap, tailwind, bulma, foundation, vanilla. data-zidan-framework/data-zs-framework.
label / hintLabel and help text. data-zidan-label, data-zidan-hint.
description / descriptionsSecondary text for card-style choices; descriptions maps radio values to text. data-zidan-description.
messagesOverride validation messages by rule name.
validate(value, field, context)Custom validation; return true, false, an error message, Error, or a Promise. Context has signal, field, and instance.
showValidStateDisplay positive async validation feedback; default false.
validationInitial valid or invalid state. data-zidan-validation.
alwaysValidateShow invalid state on native failure before blur; default false.
indeterminateInitial mixed checkbox state; default false. data-zidan-indeterminate.
clearableClear control for text/search fields; auto-enabled for search inputs. data-zidan-clear.
revealPassword visibility toggle; default false. data-zidan-reveal.
prefix / suffixText affixes displayed beside an input. data-zidan-prefix, data-zidan-suffix.
counterCharacter limit display; defaults to native maxlength. data-zidan-counter.
rowsTextarea row count; also available as the native rows attribute.
outputTarget selector for the mirrored range value. data-zidan-output.
title / dropHintFile picker title and hint; default title Choose a file. data-zidan-title, data-zidan-drop-hint.
acceptAllowed file types, read from native accept.
maxFilesMaximum selected files. data-zidan-max-files.
maxSize / maxSizeMBSize per file in bytes or MB; maxSize takes precedence. data-zidan-max-size, data-zidan-max-size-mb.
labelsMaps radio values to label fallback strings.
clearLabelClear button text; Clear all or Clear field by control.
showPasswordLabel / hidePasswordLabelPassword toggle labels; defaults Show / Hide.

Checkbox, switch, and radio options

Option / APIDescription
variantCheckbox: default, switch, card, button, minimal. Radio: stacked, inline, card, button, tile.
switchStyleSwitch skin: ios, material, square, labeled, icon. data-zidan-switch-style.
onLabel / offLabelLabels for checked and unchecked switch states. data-zidan-on-label, data-zidan-off-label.
deselectablePermit clearing the currently selected radio by clicking it again. data-zidan-deselectable.

Text, number, and phone options

Option / APIDescription
autoIconUse the icon assigned to the input type; default false. data-zidan-auto-icon.
iconRegistered icon name, SVG markup, or auto. data-zidan-icon.
iconPositionleft (default) or right. data-zidan-icon-position.
iconClickableRender a button for the icon; default false. data-zidan-icon-clickable.
iconLabelAccessible name for a clickable icon. data-zidan-icon-label.
validationIconDisplay state icons; default false. data-zidan-validation-icon.
stepperNumber stepper, default false; accepts true or stacked, split, inline. data-zidan-stepper.
stepperPositionleft or right (default) for inline steppers. data-zidan-stepper-position.
stepperWrapWrap from the maximum to the minimum and vice versa; default false. data-zidan-stepper-wrap.
stepperLongPressHold to repeat; default true. data-zidan-stepper-long-press.
stepperDelay / stepperIntervalInitial repeat delay 420 ms and repeat interval 90 ms. data-zidan-stepper-delay, data-zidan-stepper-interval.
stepperUpLabel / stepperDownLabelButton labels, default Increase value / Decrease value.
stepperStepStep override; defaults to native step.
phonePhone formatting, default off. Accepts true or an object containing country, format, showCountry, countries, and validate. data-zidan-phone.
phoneCountryISO two-letter country code; default US. data-zidan-phone-country.
phoneFormatnational, international, or e164. data-zidan-phone-format.
phoneCountrySelectShow a country selector; default true. data-zidan-phone-country-select.
phoneCountriesEnabled country list. data-zidan-phone-countries.
phoneCountryLabelSelector accessible name, default Country code.
phone.validateEnable phone-number validation; default true.

Range, date, and time options

Option / APIDescription
rangeVariantdefault, gradient, stepped, minimal. data-zidan-range-variant.
rangeBubbleShow a value bubble; default true. data-zidan-range-bubble.
rangeBubbleModeBubble visibility: always (default), active, or never. data-zidan-range-bubble-mode.
rangeBubblePositiontop (default) or bottom. data-zidan-range-bubble-position.
rangeFillShow the selected track fill; default true. data-zidan-range-fill.
rangeMinMaxShow range endpoints; default true. data-zidan-range-minmax.
rangeMinLabel / rangeMaxLabelCustom labels for the ends of the scale. data-zidan-range-min-label, data-zidan-range-max-label.
rangeTicksTick count, array, or accepted delimited string; default 0. data-zidan-range-ticks.
rangeTickLabelsShow tick values; default false. data-zidan-range-tick-labels.
rangeLabelsObject with custom tick labels.
rangeFormatString format or formatting function. data-zidan-range-format.
outputSelector for the mirrored range value. data-zidan-output.
pickerButtonDate/time native picker button; default false. data-zidan-picker-button.
pickerIconPicker icon name; depends on input type. data-zidan-picker-icon.
pickerLabelPicker button accessible name; defaults to Open <type> picker.
disableWeekendsBlock Saturday/Sunday; default false. data-zidan-disable-weekends.
disabledDatesDate list or predicate function. data-zidan-disabled-dates.
validateDate(value, date, field, context)Date validation callback; may return a boolean, message, or Promise. Context includes signal.

File upload options

Option / APIDescription
fileVariant / variantUpload layout: dropzone (default), button, avatar, gallery, compact. data-zidan-file-variant or data-zidan-variant.
uploadIconUpload-area icon; default upload. data-zidan-upload-icon.
upload / uploadHandlerCustom upload function (file, context). Return a Promise/result or complete via context helpers.
uploadUrlMultipart POST endpoint. data-zidan-upload-url.
uploadFieldMultipart file field name; default file. data-zidan-upload-field.
uploadDataAdditional multipart fields; object or (file, field) => object.
withCredentialsXHR credential flag; default false. data-zidan-with-credentials.
uploadHeaders / headersRequest headers object or callback.
simulateUploadLocal progress simulation; default false. data-zidan-simulate-upload.
simulateDurationSimulation duration, default 900 ms. data-zidan-simulate-duration.
autoUploadUpload immediately after selection; default true. data-zidan-auto-upload.
showFileMetaDisplay file rows; default true. data-zidan-show-file-meta.
showPreview / preview / previewsImage preview settings; default true. data-zidan-preview.
replaceTitleAvatar replacement label; default Change image.
progressTemplateProgress label, default Uploading {percent}%.
uploadedLabelCompleted upload label; default Uploaded.
failedLabelFailed upload label; default Upload failed.
canceledLabelCanceled upload label; default Upload canceled.
cancelLabel / retryLabelAction labels; default Cancel / Retry.
renderFilePer-file renderer (itemElement, { file, index, state, field }).

Select and combobox options

Option / APIDescription
modeselect (default), combobox, or tags. data-zidan-select/data-zidan-mode.
layoutSelect layout; default classic-clean. data-zidan-layout.
themeFrameworkFramework skin: auto, none, vanilla, bootstrap, tailwind, bulma, foundation; default auto. data-zidan-framework.
themeTheme preset; default default. data-zidan-theme.
idGenerated wrapper root ID prefix.
nameName for mount-mode hidden input; defaults to native name. data-zidan-name.
disabled / requiredInitial states; mirror native attributes. data-zidan-disabled for disabled.
validationnull (default), valid, or invalid. data-zidan-validation.
scrollbardefault (default), thin, fancy, hover, hidden. data-zidan-scrollbar.
customClassesClass map for root, control, input; default empty map.
optionsArray of strings or { value, label, disabled?, group? }.
suggestionsSuggested tag values.
valueInitial value or array for multiple/tags.
label / ariaLabelVisible/floating and accessible label; ariaLabel defaults to label. data-zidan-label.
placeholderPlaceholder text. data-zidan-placeholder.
multipleMulti-select mode; reflects native multiple. data-zidan-multiple.
searchableSearch input; defaults to false for plain select mode, otherwise true. data-zidan-searchable.
clearableClear button; default false. data-zidan-clearable.
closeOnSelectClose the list after selection, default true for single selection.
maxDropdownHeightList height limit, default 280 pixels.
noResultsTextEmpty filtered-results text, default No results found.
emptyTextNo-source-options text, default No options.
loadingTextRemote loading status, default Searching….
clearTextClear button label, default Clear selection.

Remote select options

Option / APIDescription
fetchOptions(query, signal, context)Async data callback; return items or { items, hasMore }/{ items, total }. Context includes page, pageSize, append, instance.
fetchPageSizePagination size; default 0 (single request). data-zidan-fetch-page-size.
fetchUrlAuto-fetch endpoint; default null. data-zidan-fetch-url.
fetchQueryParamQuery parameter; default q. data-zidan-fetch-query-param.
fetchPageParamPage parameter; default page. data-zidan-fetch-page-param.
fetchSkipParamOffset parameter alternative; default null. data-zidan-fetch-skip-param.
fetchPageSizeParamLimit parameter; default limit. data-zidan-fetch-page-size-param.
fetchItemsPathResponse item-list dot path; default null. data-zidan-fetch-items-path.
fetchTotalPathTotal-count path; default null. data-zidan-fetch-total-path.
fetchHasMorePathMore-results boolean path; default null. data-zidan-fetch-has-more-path.
fetchMethodHTTP method, default GET. data-zidan-fetch-method.
fetchHeadersHTTP request headers; default null.
fetchCredentialsFetch credentials, default same-origin.
autoLoadMoreLoad next page near the list bottom; default true.
loadMoreTextFooter text; default Load more.
cacheResultsCache query/page results; default true.
debounceRequest delay, default 250 ms.
minCharsMinimum search length before fetch; default 0.
searchValuesSearch option values and labels; default true.

Tag and rendering options

Option / APIDescription
maxTagsMaximum tag count; default Infinity. data-zidan-max-tags.
minTagLengthMinimum characters per tag; default 1. data-zidan-min-tag-length.
maxTagLengthMaximum characters per tag; default Infinity. data-zidan-max-tag-length.
caseSensitiveCase-sensitive duplicate handling; default false. data-zidan-case-sensitive.
allowFreeTextAccept tags outside options/suggestions; default true. data-zidan-allow-free-text.
delimitersTag delimiters; default [','].
commitOnTab / commitOnBlurAdd current text as a tag on Tab/blur; default false.
valueDelimiterValue serialization delimiter; default comma.
filterOption(item, query)Custom option filter; returns boolean.
renderOption(item, context)Custom listbox item HTML or element.
renderSelected(item, context)Custom selected item HTML or element.
renderTag(item, context)Custom tag HTML or element.
validateTag(tag, tags, context)Return true or an error string.
formatTag(tag, context)Return formatted tag display string.

Automatic initialization options

Option / APIDescription
window.ZIDAN_FORM_CONFIGGlobal configuration before script loading; ZIDAN_SELECT_CONFIG is an alias.
autoInitSet false to disable automatic scanning. data-zidan-auto-init="false" on <html> also works.
targets / selectorsSelect elements by ID, class, selector string, or { selector, options }.
fieldTargetsTarget supported input/textarea elements, with optional per-target settings.
formTargetsAdditional scopes in which selects and file inputs are initialized.
optionsShared select settings for the scan.
fieldOptions / fieldsShared field options; fields is the legacy alias.
selectorLegacy single select selector; skips the generic attribute scan.
data-zidan-optionsJSON options on any supported marked element.
marker classeszidan-select (select), zidan-field (field), zidan-form (scope).
data-zidan-formAttribute marking a scope that scans native selects and file inputs.

JavaScript API

Global functions and managers

Option / APIDescription
zidanSelect(target, options?)Initialize one or more select elements; returns one instance or an array.
initZidanSelects(scope?, options?)Initialize marked selects in a scope; returns ZidanSelect[].
initZidanForms(scope?, options?)Initialize marked fields in a scope; returns a field array.
zidanField(target, options?)Initialize supported field(s), including unmarked inputs; returns an instance, null when unmatched, or an array for multiple targets.
ZidanForm.init(scope, options)Initialize supported fields in a scope.
ZidanForm.field(target, options)Initialize targeted field(s).
ZidanForm.get(input)Retrieve a field instance or null.
ZidanForm.refresh(scope?)Scan for new fields and synchronize existing fields.
ZidanForm.observe(scope, options?)Observe DOM changes; returns MutationObserver or null.
ZidanForm.destroyAll()Destroy all enhanced fields.
ZidanForm.registerIcon(name, svg)Register icon SVG markup for input adornments.
registerIcon(name, svg) / registerZidanIcon(name, svg)Named exports/browser registration helpers for custom icons.
formatPhone(value, country?, format?)Phone formatting helper exported by the module.
detectPhoneCountry(value)Detect a phone country from input text where supported.
ZidanForm.themes / fieldLayouts / frameworksAvailable names; themes and fieldLayouts support custom name registration.
ZidanForm.variants / stepperModes / phoneFormats / phoneCountriesPublic accepted variants, modes, formats, and phone-country registry.
ZidanForm.icons / messagesBuilt-in icon and validation-message registries.
ZidanSelect.get(input)Retrieve a select instance.
ZidanSelect.destroyAll()Destroy all select instances.
ZidanSelect.instances / layouts / frameworks / scrollbarsSelect instance registry and accepted layout, framework, scrollbar names.
ZidanSelect.cacheLimitMaximum cached remote pages; default 50.

Select instance methods

Option / APIDescription
open() / close() / toggle() / isOpen()Control the listbox visibility or read whether it is open.
getValue() / setValue(value)Read or change the selected value; arrays for multiple/tag modes.
clear()Clear selected value(s).
setOptions(items)Replace options in both the display and native <option> list.
addTag(value) / removeTag(value) / getTags()Add, delete, or read tags in tags mode.
enable() / disable()Toggle available input state.
setLayout(name) / setFramework(name) / setScrollbar(name)Change select appearance settings.
setValidation(state)Set valid/invalid state or clear it with null.
refresh()Re-read current native select state.
loadMore() / hasMoreResults()Load next remote page / read whether one remains.
getAsyncState()Read remote loading and pagination state.
refreshOptions() / clearCache()Reload remote choices / purge cached pages.
on(event, handler) / off(event, handler)Register or remove instance event handlers.
announce(message)Announce a status through the select live region.
destroy()Remove generated UI, restore the native control, and release listeners.

Field instance methods

Option / APIDescription
getValue() / setValue(value)Read/update native input, checked, radio, or file state.
update() / refresh()Re-read native state and update the enhanced field.
validationTargets()Native elements used for mirrored constraints.
setValidation(state) / getValidation()Set/read valid, invalid, or cleared state.
setError(message) / clearError()Set or clear visible error feedback.
checkAsync()Run pending custom validation; returns a Promise.
validate() / isPending()Run native and custom rules / read pending state.
setTheme(name) / setFramework(name) / setLayout(name)Change one field’s styling.
setIndeterminate(value) / setChecked(value) / isChecked()Checkbox state helpers.
stepUp(times?) / stepDown(times?) / setStepper(enabled)Number step controls.
getPhoneCountry() / setPhoneCountry(iso) / setPhoneFormat(format) / formatPhone(value?)Phone-country and formatting helpers.
openPicker() / showPicker()Open the native date/time picker when available.
getFiles() / getUploadState()Read file list and upload results/status.
addFiles(files) / replaceFiles(files) / removeFile(nameOrIndex) / clear()Modify selected files.
setVariant(name) / setUploader(functionOrUrl)Change file layout or upload handler.
uploadAll() / uploadFile(file) / cancelUpload(file) / cancelAll() / retryUpload(file)Upload lifecycle controls.
destroy()Restore the original input and release listeners and any ongoing async work.

Callbacks

Callbacks are configured in JavaScript options. Every callback receives an object with the instance and the relevant value, item, file, or lifecycle fields.

Option / APIDescription
onInitSelect: { instance, mode, value }; field: { instance, variant?, type? }.
onChangeSelect: value and previousValue; field: value, checked, or files.
onInputField input and range value.
onValidation{ instance, state, message? }.
onSelectSelected value and item.
onOpen / onCloseSelect visibility changes; receives instance.
onTagAdd / onTagRemoveTag and selected value.
onLoadMorePage and query when remote pagination begins.
onErrorError message and error/callback details.
onIconClickIcon name and position.
onStepNumber value and step direction.
onPickerDate/time input type.
onPhoneCountry / onPhoneFormatCountry selection and phone format.
onRemoveRemoved file and index.
onUploadStart / onUploadProgress / onUploadSuccessFile, name, and size/progress/result information.
onUploadAlias for onUploadSuccess.
onUploadError / onUploadCancelFile, name, and error information where available.

DOM events

Custom events bubble from the generated field wrapper. Read their payload from event.detail. Native change events also work on the original inputs.

document.addEventListener('zidan:change', (event) => {
  console.log(event.detail.value);
});
document.addEventListener('zidan:upload-progress', (event) => {
  console.log(event.detail.name, event.detail.progress);
});
Option / APIDescription
zidan:init / zidan:destroyInstance lifecycle.
zidan:change / zidan:inputChanged value, checked state, files, or input text.
zidan:validation / zidan:async-validationValidity state, async rule result, and message.
zidan:open / zidan:close / zidan:selectSelect opened/closed or an item was selected.
zidan:no-resultsSelect query returned no matches.
zidan:tag-add / zidan:tag-removeTag and value information.
zidan:load-moreRemote query and next page.
zidan:revealPassword reveal visibility.
zidan:clear / zidan:removeCleared control or removed file.
zidan:stepNumber value, direction, and step.
zidan:phone-country / zidan:phone-formatUpdated phone country or format.
zidan:icon-click / zidan:pickerIcon action or native date/time picker request.
zidan:upload-start / zidan:upload-progressFile upload started or made progress.
zidan:upload-success / zidan:upload-error / zidan:upload-cancelCompleted, failed, or canceled upload.
zidan:errorPlugin error, callback, and instance context.

Themes and Styling

Choose default, modern, minimal, dark, or glass with data-zs-theme. Set data-zs-framework to bootstrap, tailwind, bulma, or foundation for the corresponding CSS adapter. Values resolve from the control to its ancestors and then <html>.

<form data-zs-theme="dark" data-zs-framework="bootstrap">
  <select name="region" data-zidan-select="select" data-zidan-layout="soft-pill">
    <option value="west">West</option>
    <option value="east">East</option>
  </select>
</form>

Customize a preset by overriding the published --zs-* tokens after the theme stylesheet.

.signup-form {
  --zs-primary: #d93854;
  --zs-primary-soft: #fff2f4;
  --zs-radius: 12px;
  --zs-focus-ring: rgba(217, 56, 84, 0.2);
}

Public layout and styling hooks

Option / APIDescription
select layoutsclassic-clean, floating-label, soft-pill, bordered-brutalist, glass-elevated.
field layoutsstacked, inline, compact, floating, outlined, card.
scrollbar variantsdefault, thin, fancy, hover, hidden.
zidan-select / zidan-field / zidan-formPublic marker classes for automatic enhancement and scoped initialization.
zs-form-grid / zs-fullPublic wrapper grid and a field-span modifier; grid is not a field layout value.
zs-native-inputNative control retained inside the generated wrapper.
zs-field--invalid / zs-field--valid / zs-field--pendingValidation-state hooks; pending also sets aria-busy.
zs-range-scale--hidden / zs-range--labels-no-scaleRange scale hidden or spacing reserved when tick labels replace endpoints.
zs-range-tick--start / zs-range-tick--endMark endpoint tick labels in range controls.
zs-range-bubble--start / zs-range-bubble--endBubble-edge positioning hooks for range controls.
data-zs-validationReflected validation state on rendered fields.
ZidanForm.registerIcon(name, markup)Register an SVG icon for use with icon and uploadIcon.

CSS custom properties

Option / APIDescription
--zs-font-family / --zs-font-size / --zs-line-heightTypography: inherit / 0.9375rem / 1.4.
--zs-label-size / --zs-heightLabel size (0.8125rem) / field height (44px).
--zs-radius / --zs-chip-radiusField and chip radii: 10px / 8px.
--zs-border-width / --zs-gapBorder thickness 1px / spacing 6px.
--zs-padding-x / --zs-padding-yHorizontal / vertical input padding: 12px / 5px.
--zs-dropdown-radius / --zs-dropdown-border-widthDropdown radius 12px / border width 1px.
--zs-option-radius / --zs-option-padding-x / --zs-option-padding-yOption radius 8px, padding 12px / 9px.
--zs-bg / --zs-text / --zs-text-muted / --zs-placeholderControl backgrounds, foreground text, muted text, placeholders.
--zs-border-color / --zs-border-color-hover / --zs-border-color-focusNormal, hover, and focus borders.
--zs-border-color-invalid / --zs-border-color-validValidation border colors.
--zs-primary / --zs-primary-contrast / --zs-primary-softAccent, contrast text, and light accent surfaces.
--zs-focus-ring / --zs-focus-ring-widthFocus-ring color and width.
--zs-chip-bg / --zs-chip-text / --zs-chip-borderSelected tag styling.
--zs-dropdown-bg / --zs-dropdown-border / --zs-dropdown-shadowDropdown surfaces and shadow.
--zs-option-hover-bg / --zs-option-active-bg / --zs-option-active-textHover and keyboard-active option colors.
--zs-option-selected-bg / --zs-option-selected-text / --zs-group-textSelected option and group label colors.
--zs-check-size / --zs-check-radius / --zs-check-gapCheckbox geometry.
--zs-check-bg / --zs-check-border / --zs-check-markCheckbox background, border, and mark.
--zs-check-checked-bg / --zs-check-checked-borderChecked-checkbox styles.
--zs-switch-width / --zs-switch-height / --zs-switch-off / --zs-switch-knobSwitch track geometry and colors.
--zs-switch-width-lg / --zs-switch-height-lgLarger switch geometry.
--zs-switch-on-text / --zs-switch-off-textSwitch labels.
--zs-radio-size / --zs-radio-border / --zs-radio-gapRadio geometry.
--zs-file-drop-bg / --zs-file-drop-borderFile drop target colors.
--zs-file-thumb-bg / --zs-file-thumb-textFile thumbnail colors.
--zs-field-gapSpacing in a field; default 6px.
--zs-icon-color / --zs-icon-hover-bgIcon and icon button styling.
--zs-stepper-color / --zs-stepper-hover-bgNumber stepper buttons.
--zs-phone-borderPhone-country selector separator.
--zs-radius-pillRounded button/check/radio skin, default 999px.
--zs-avatar-size / --zs-avatar-bg / --zs-avatar-borderAvatar file target size/background/border.
--zs-range-track / --zs-range-fill / --zs-range-gradientRange slider track and fill.
--zs-range-thumb-bg / --zs-range-thumb-borderRange slider thumb styles.
--zs-range-tick / --zs-range-tick-textRange tick colors.
--zs-range-bubble-bg / --zs-range-bubble-textRange bubble styling.
--zs-range-angleRTL-aware gradient angle.
--zs-upload-track / --zs-upload-bar / --zs-upload-successUpload progress and success colors.

Lifecycle and Integration

The original inputs remain the source of truth for values, FormData, file lists, validation, and form.reset(). Call refresh() after programmatic native-state changes; observe dynamic subtrees when controls are inserted later.

For React, Vue, or Angular, initialize after mount and destroy the instances before unmount. In Next.js, keep form initialization in a client component after hydration.

const observer = ZidanForm.observe(document.querySelector('#dialog-body'));
// Before removing the observed container:
observer.disconnect();
ZidanForm.destroyAll();

Alternatives and Related Resources

You Might Be Interested In:


Leave a Reply