Documentation · reference

Options & data attributes

Every JS option, data attribute, callback, event and instance method.

Options & data attributes

Everything is opt-in. A control is enhanced only when it carries a data-zidan* attribute, carries a marker class, sits inside a form scope, is matched by a configured target, or is passed to initZidanSelects() / initZidanForms() / zidanSelect() / zidanField(). zidanField() itself accepts any supported <input>/<textarea>, with or without a data-zidan* attribute, which is how JS-only options are applied.

Prefer to click through the options? The field playground exposes the main options for one control at a time and copies both supported HTML attributes and vanilla JavaScript. The API lab exercises the complete option, callback, method and event inventory.

Direct init by ID or class

The first argument of zidanSelect() accepts a CSS selector, an element, or a NodeList. Plain selects are not auto-initialised, so you can enhance exactly the field you want. For complete copy-paste pages (static HTML, WordPress, page builders) see the static HTML & WordPress cookbook.

<select id="mymov">…</select>
<select class="mymovclass">…</select>
<select class="mymovclass">…</select>
const picker = zidanSelect('#mymov', {
  mode: 'combobox',
  label: 'Movie',
  placeholder: 'Search a movie…',
  searchable: true,
  clearable: true
});

const pickers = zidanSelect('.mymovclass', { mode: 'select', layout: 'soft-pill' });
// one match → instance, several → array

initZidanSelects(scope, options) still bulk-enhances every [data-zidan-select] and .zidan-select inside a scope; use it when the markup can carry attributes. zidanSelect() is the targeted form for IDs, classes and elements you already have a reference to.

Read values and option details

picker.getValue();                 // selected value; array for multiple/tags
picker.setValue('dune');
picker.getTags();                  // tags mode

const native = picker.el;          // the original <select>
native.selectedOptions;            // selected <option> elements
Array.from(native.options).map(option => ({
  value: option.value,
  label: option.text,
  disabled: option.disabled,
  group: option.parentElement.tagName === 'OPTGROUP' ? option.parentElement.label : null
}));

picker.setOptions([                // rebuilds listbox and native <option>s
  { value: 'inception', label: 'Inception' },
  { value: 'dune', label: 'Dune', group: 'Villeneuve' },
  { value: 'arrival', label: 'Arrival', disabled: true }
]);

Listen to the library callback in the options (onChange: ({ instance, value }) => …) or to the native change event; the native <select> always holds the current value.

No-JS init (IDs, classes, selectors, JSON)

For CMS templates where attributes are limited and custom scripts are unwelcome, init can be entirely declarative. The same rules apply to the full build, the select-only bundle and the file-only bundle.

PathMarkupWhat is enhanced
Marker class<select class="zidan-select">That select, or a mount <div>. Mode comes from data-zidan-options / data-zidan-mode.
Marker class<input class="zidan-field">A checkbox, file or text/textarea input. Put it on the <fieldset> for a radio group.
Form wrapper<form class="zidan-form"> or data-zidan-form on any elementEvery <select> and every <input type="file"> inside, marked or not.
Config targetswindow.ZIDAN_FORM_CONFIG (alias ZIDAN_SELECT_CONFIG)Anything matched by an ID, class or full CSS selector.

data-zidan-options JSON

Plain options as JSON on the element itself, for selects and every field type:

<select class="zidan-select" multiple
        data-zidan-options='{"mode":"tags","maxTags":3,"placeholder":"Add a tag…"}'>…</select>

<input type="file" class="zidan-field"
       data-zidan-options='{"variant":"gallery","maxFiles":4,"title":"Add images"}'>

Values must be literal JSON; callbacks, upload functions and raw SVG icon markup still need a small JS block. Invalid JSON is ignored with one console warning.

window.ZIDAN_FORM_CONFIG

KeyTypeEffect
autoInitbooleanfalse disables every automatic pass (data-zidan-auto-init="false" does the same).
targets / selectorsstring or arrayCSS selectors, or { selector, options } entries, initialised as selects.
fieldTargetsstring or arraySelectors initialised as fields; plain text inputs and textareas are accepted.
formTargetsstring or arrayExtra form scopes: every select and file input inside is initialised.
optionsobjectShared select options for the attribute scan and for targets.
fieldOptionsobjectShared field options for the scan and for targets.
fieldsobjectLegacy alias of fieldOptions.
selectorstringLegacy: initialise only these selects and skip the attribute scan.
window.ZIDAN_FORM_CONFIG = {
  targets: ['#country', 'select.product-variants',
            { selector: '#brands', options: { mode: 'tags', maxTags: 3 } }],
  fieldTargets: [
    { selector: '#avatar', options: { variant: 'avatar' } },
    { selector: 'input[name="email"]', options: { icon: 'mail' } }
  ],
  formTargets: ['#checkout']
};

Precedence for any single option: per-target options → data-zidan-options JSON → data-zidan-* attribute → default. Config is read during the DOMContentLoaded pass, so set it before the library script (or call initZidanSelects() / initZidanForms() yourself with the same values). Explicit targets run first so their options win over the generic scan.

Field options

Applies to ZidanCheckbox, ZidanRadioGroup, ZidanFileUpload, ZidanTextField.

JS optionData attributeTypeDefaultNotes
variantdata-zidan-variantstringdefaultCheckbox: default, switch, card, button, minimal. Radio: stacked, inline, card, button, tile. File: dropzone, button, avatar, gallery, compact. Range uses rangeVariant.
layoutdata-zidan-layoutstringstackedstacked, inline, compact, floating, outlined, card.
themedata-zidan-theme, data-zs-themestringdefaultdefault, modern, minimal, dark, glass. Resolves element → ancestor → <html>.
frameworkdata-zidan-framework, data-zs-frameworkstringnonenone, bootstrap, tailwind, bulma, foundation, vanilla.
labeldata-zidan-labelstring—Used when the markup has no <label>; a generated label is <label for>. If the markup already has a <label>, the generated one replaces it and the original is hidden until destroy().
hintdata-zidan-hintstring—Rendered under the control and linked via aria-describedby.
descriptiondata-zidan-descriptionstring—Second line for card, tile, button and minimal checkbox/radio variants.
descriptions—object—Radio group: { value: 'Description' } fallback descriptions.
messages—object—Override built-in validation messages, including required, phone, weekend and generic.
validate(value, field, context)—function—Custom rule for text, checkbox, radio or file fields. Return true, false, a message string, Error or Promise; context is { signal, field, instance }.
showValidState—booleanfalseShow a positive state after a successful async rule.
validationdata-zidan-validationvalid \invalid—Initial state; later states come from validity or setValidation(). A preset invalid survives update() / refresh() and internal mirrors until user input/change/blur or setValidation(null); programmatic value helpers that dispatch change, and a non-empty select value, also clear it.
alwaysValidate—booleanfalseMark invalid as soon as native validity fails instead of on blur.
indeterminatedata-zidan-indeterminatebooleanfalseCheckbox starts mixed.
clearabledata-zidan-clearbooleansearch onlyClear button for text inputs and textarea.
revealdata-zidan-revealbooleanfalsePassword show/hide toggle.
prefixdata-zidan-prefixstring—Static text before the input.
suffixdata-zidan-suffixstring—Static text after the input.
counterdata-zidan-counternumbermaxlengthCounter maximum; wins over the maxlength default.
outputdata-zidan-outputselector—Range display value (formatted when rangeFormat is set) is mirrored into this element.
titledata-zidan-titlestringChoose a fileDropzone headline.
dropHintdata-zidan-drop-hintstring—Dropzone subtitle.
acceptnative acceptstring—Validated on top of the native picker filter and shown in the dropzone hint.
maxFilesdata-zidan-max-filesnumber—Extra files are trimmed and reported.
maxSizedata-zidan-max-sizenumber—Bytes per file.
maxSizeMBdata-zidan-max-size-mbnumber—Megabytes per file; 2 = 2 MB, decimals allowed. Ignored when maxSize is set.
labels—object—Radio group: { value: 'Label' } fallback labels.
clearLabel—stringClear all / Clear fieldButton text/aria-label.
showPasswordLabel—stringShowPassword toggle labels.
hidePasswordLabel—stringHidePassword toggle labels.

Field callbacks

CallbackPayload
onInit{ instance, variant?, type? }
onChange{ instance, value } (text/radio), { instance, checked, value } (checkbox), { instance, files } (file)
onInput{ instance, value } (text/range)
onValidation{ instance, state, message? } where state is valid, invalid or null
onIconClick{ instance, icon, position }
onStep{ instance, value, direction }
onPicker{ instance, type }
onPhoneCountry{ instance, country }
onPhoneFormat{ instance, format }
onRemove{ instance, file, index }
onUploadStart / onUploadProgress / onUploadSuccess{ instance, file, name, ... } with size, progress or result
onUploadAlias of onUploadSuccess.
onUploadError / onUploadCancel{ instance, file, name, error?, message? }

DOM events with the same information: zidan:init, zidan:change, zidan:input, zidan:validation, zidan:async-validation, zidan:remove, zidan:reveal, zidan:clear, zidan:icon-click, zidan:step, zidan:picker, zidan:phone-country, zidan:phone-format, zidan:upload-*, zidan:destroy and zidan:error.

Checkbox, switch & radio variants

ControlOption / attributeValuesNotes
Checkbox / switchvariant / data-zidan-variantdefault, switch, card, button, minimalbutton is a filter-style pill; minimal removes the border for dense lists.
SwitchswitchStyle / data-zidan-switch-styleios, material, square, labeled, iconSkin only — combine with variant="switch".
SwitchonLabel / data-zidan-on-labelstringlabeled and icon styles: checked text.
SwitchoffLabel / data-zidan-off-labelstringlabeled and icon styles: unchecked text.
Checkbox / radiodescription / data-zidan-descriptionstringSecond line under the label (card, tile, button, minimal).
Radio groupvariant / data-zidan-variantstacked, inline, card, button, tileApplies to the <fieldset>.
Radio groupdeselectable / data-zidan-deselectablebooleanClicking the selected radio clears the group.

ZidanForm.variants exposes the accepted names: { checkbox: [...], switch: [...], radio: [...], file: [...], range: [...] }.

Text input: icons

Supports text, email, password, number, tel, url, search, date, time, datetime-local, month, week, range, color and <textarea>.

JS optionData attributeTypeDefaultNotes
autoIcondata-zidan-auto-iconbooleanfalseUses the built-in icon for the input type (mail, phone, calendar, clock, search, link, hash, palette).
icondata-zidan-iconstring—Any registered name, a raw <path>/SVG string, or "auto" (same as autoIcon).
iconPositiondata-zidan-icon-positionleft \rightleftRight icons sit after suffix/actions.
iconClickabledata-zidan-icon-clickablebooleanfalseRenders a <button> and emits zidan:icon-click. Date/time pickers are always clickable.
iconLabeldata-zidan-icon-labelstring—Accessible name for a decorative/custom icon.
validationIcondata-zidan-validation-iconbooleanfalseAdds check/alert glyphs driven by [data-zs-validation].
<!-- type-based icon -->
<input type="email" data-zidan="input" data-zidan-auto-icon="true" data-zidan-clear>

<!-- custom icon, right side, clickable -->
<input type="url" data-zidan="input" data-zidan-icon="link"
       data-zidan-icon-position="right" data-zidan-icon-clickable="true"
       data-zidan-icon-label="Open website">
// register your own icon (path markup or a full <svg>), then use its name anywhere
ZidanForm.registerIcon('sparkle', '<path d="M12 3l1.9 5.3L19 10l-5.1 1.7L12 17Z"/>');
window.registerZidanIcon('heart', '<path d="M12 20s-7-4.4-7-9a4 4 0 0 1 7-2 4 4 0 0 1 7 2c0 4.6-7 9-7 9Z"/>');

// or configure a plain input entirely from JavaScript
zidanField('#brand', {
  icon: 'palette',
  iconPosition: 'right',
  iconClickable: true,
  iconLabel: 'Pick a brand colour'
});

Built-in names: text, mail, phone, user, lock, search, calendar, clock, link, hash, palette, sliders, file, upload, eye, eye-off, check, x, plus, minus, chevron-down, chevron-up, chevron-left, chevron-right, alert, info, globe, map-pin, image, refresh, trash. icon also accepts raw <path> or <svg> markup.

Icons are sanitised with DOMParser: only SVG shape elements and safe attributes survive.

Number stepper (− / +)

JS optionData attributeTypeDefaultNotes
stepperdata-zidan-stepperboolean \modefalsetrue = stacked; or stacked, split, inline. Any value except false/"false" enables it.
stepperPositiondata-zidan-stepper-positionleft \rightrightinline mode only.
stepperWrapdata-zidan-stepper-wrapbooleanfalseAdds a wrapping border around the field (theme hook).
stepperLongPressdata-zidan-stepper-long-pressbooleantruePress and hold repeats.
stepperDelaydata-zidan-stepper-delaynumber420Hold delay before repeating, ms.
stepperIntervaldata-zidan-stepper-intervalnumber90Repeat interval, ms.
stepperUpLabeldata-zidan-stepper-up-labelstringIncrease valueAria-label of “+”.
stepperDownLabeldata-zidan-stepper-down-labelstringDecrease valueAria-label of “−”.
stepperStep—numbernative stepIncrement used by the stepper buttons and stepUp() / stepDown().
<input type="number" min="0" max="10" value="3" data-zidan="input"
       data-zidan-stepper="stacked">
<input type="number" min="0" max="99" data-zidan="input"
       data-zidan-stepper="split">
<input type="number" step="0.5" data-zidan="input"
       data-zidan-stepper="inline" data-zidan-stepper-position="left">

Methods: stepUp(times = 1), stepDown(times = 1), setStepper(enabled). setStepper() toggles the source attribute; destroy and reinitialise the field to add or remove the generated stepper buttons. Event: zidan:step → { value, direction, instance }.

Phone formatting

JS optionData attributeTypeDefaultNotes
phonedata-zidan-phoneboolean \objectfalseEnables formatting. Object form: { country, format, showCountry, countries, validate }.
phoneCountrydata-zidan-phone-countryISO-2USOne of ZidanForm.phoneCountries.
phoneFormatdata-zidan-phone-formatnational \international \e164nationalThree styles per country.
phoneCountrySelectdata-zidan-phone-country-selectbooleantrueShow the native country <select>.
phoneCountriesdata-zidan-phone-countrieslistcommon setComma-separated ISO codes for the selector.
phoneCountryLabel—stringCountry codeAria-label for the selector.
phone.validate—booleantrueLength check per country (uses messages.phone).
<input type="tel" data-zidan="input" data-zidan-phone="true"
       data-zidan-phone-country="GB" data-zidan-phone-format="international"
       data-zidan-phone-country-select="false">

Methods: getPhoneCountry(), setPhoneCountry('GB'), setPhoneFormat('e164'), formatPhone(value?). Events: zidan:phone-country → { country }, zidan:phone-format → { format }.

Static helpers:

ZidanForm.formatPhone('2025550134', 'US', 'e164');        // +12025550134
ZidanForm.detectPhoneCountry('+44 7700 900123');          // 'GB'

Formatting is caret-safe: digits are re-masked around the caret while typing, and a leading national 0 is dropped in international/E.164 output.

Range inputs

JS optionData attributeTypeDefaultNotes
rangeVariantdata-zidan-range-variantdefault \gradient \stepped \minimaldefaultVisual skin.
rangeBubbledata-zidan-range-bubblebooleantrueMaster switch for the floating value bubble.
rangeBubbleModedata-zidan-range-bubble-modealways \active \neveralwaysactive shows the bubble only on hover, focus or drag.
rangeBubblePositiondata-zidan-range-bubble-positiontop \bottomtopBubble above the track or below the ticks/scale.
rangeFilldata-zidan-range-fillbooleantrueColoured progress fill; false keeps the neutral track (gradient skin keeps its gradient).
rangeMinMaxdata-zidan-range-minmaxbooleantrueMin/max scale under the track. Hidden automatically when labeled ticks cover both ends, so 0 and the max print once.
rangeMinLabel / rangeMaxLabeldata-zidan-range-min-label / -range-max-labelstring—Custom text for the scale ends (e.g. Low / High); rangeFormat is used when unset.
rangeTicksdata-zidan-range-ticksnumber \array \string0Count, JS array, JSON array or comma list (0,250,500). Values are absolute and out-of-range ones sit at the nearest end.
rangeTickLabelsdata-zidan-range-tick-labelsbooleanfalseText labels on ticks. Labels at both ends replace the min/max scale.
rangeLabels—object—Map { value: 'Label' } used with labeled ticks.
rangeFormatdata-zidan-range-formatstring \function—Template with {value}, {min}, {max} (or %s), or function(value, field) in JS.
outputdata-zidan-outputselector—Mirrors the display value (formatted when rangeFormat is set) into a <output>/element; input.value keeps the raw value.
<input type="range" min="0" max="1000" step="50" value="400"
       data-zidan="input" data-zidan-range-variant="minimal"
       data-zidan-range-minmax="false" data-zidan-output="#budget">
zidanField('#price', {
  rangeVariant: 'gradient',
  rangeTicks: [0, 250, 500, 750, 1000],
  rangeTickLabels: true,
  rangeLabels: { 0: 'Free', 1000: 'Top' },
  rangeFormat: value => '€' + Number(value).toLocaleString('en-US')
});

zidanField('#delivery', {
  rangeBubbleMode: 'active',      // 'always' | 'active' | 'never'
  rangeBubblePosition: 'bottom',  // 'top' | 'bottom'
  rangeFill: false,               // neutral track, no progress colour
  rangeTicks: '0,10,20,30',       // count, array, JSON or comma list
  rangeTickLabels: true,
  rangeMinLabel: 'Low',
  rangeMaxLabel: 'High'
});

The range keeps input.value native; only the visual chrome and bubble are added. Instance properties range, rangeBubble, rangeTicksEl and rangeScale are exposed if you need to re-render custom ticks.

Labeled ticks and the scale do not stack: when rangeTickLabels is on and the tick values include both min and max, the scale row (.zs-range-scale) gets zs-range-scale--hidden and the tick labels are the single endpoint readout. rangeLabels entries win over rangeFormat for that value. Endpoint labels carry zs-range-tick--start / --end and the bubble gets zs-range-bubble--start / --end, so both stay inside the track at 0 and max, including in RTL. Without a scale row (.zs-range--labels-no-scale) the label height is reserved so labels cannot overlap the next element.

Bubble behaviour is controlled by rangeBubbleMode (always / active / never) and rangeBubblePosition (top / bottom), the coloured progress by rangeFill, and the scale ends by rangeMinLabel / rangeMaxLabel. rangeFill: false keeps the neutral track but not the gradient skin, and rangeFormat also feeds aria-valuetext so assistive tech reads the formatted value.

Date & time pickers

JS optionData attributeTypeDefaultNotes
pickerButtondata-zidan-picker-buttonbooleanfalseAdds a picker button when no icon is present.
pickerIcondata-zidan-picker-iconstringper typeAny registered icon (default calendar/clock).
pickerLabel—stringOpen <type> pickerAria-label for the picker button.
disableWeekendsdata-zidan-disable-weekendsbooleanfalseSat/Sun fail validation with messages.weekend.
disabledDatesdata-zidan-disabled-dateslist \function—Comma-separated ISO dates, array, or (value, date, field) => true in JS.
validateDate—function—`(value, date, field) => boolean \string; return false for messages.date` or a custom string.
<input type="date" value="2026-11-23" data-zidan="input"
       data-zidan-icon="calendar" data-zidan-icon-position="left"
       data-zidan-disable-weekends="true">
<input type="datetime-local" data-zidan="input" data-zidan-picker-button="true"
       data-zidan-picker-icon="calendar">

Methods: openPicker() / showPicker(). Event: zidan:picker → { type }.

The native picker is used via input.showPicker() when available; icons keep the native input reachable, so form values and validation stay native.

File upload: variants, uploading & rendering

Variants are set with fileVariant / data-zidan-file-variant (defaults to dropzone):

VariantDesign
dropzoneFull-width dashed target; thumbnail or extension badge in the list.
buttonEntire target is a compact button, one row.
avatarCircular 96 px target with a single-image preview (--zs-avatar-size to resize).
galleryWrap target plus a responsive thumbnail grid.
compactOne-line target for sidebars; combine with showFileMeta: false.
JS optionData attributeTypeDefaultNotes
fileVariantdata-zidan-file-variantstringdropzonedropzone, button, avatar, gallery, compact.
uploadIcondata-zidan-upload-iconstringuploadIcon in the drop target (any registered name or icon).
upload / uploadHandler—function—Custom uploader, see contract below.
uploadUrldata-zidan-upload-urlstring—XHR endpoint; POST multipart.
uploadFielddata-zidan-upload-fieldstringfileFormData field name.
uploadData—object \function—Extra FormData fields ((file, field) => object).
withCredentialsdata-zidan-with-credentialsbooleanfalseXHR credentials.
uploadHeaders / headers—object \function—Extra request headers ((file, field) => object).
simulateUploaddata-zidan-simulate-uploadbooleanfalseVisual upload only; files never leave the browser.
simulateDurationdata-zidan-simulate-durationnumber900Simulation length, ms (min 120).
autoUploaddata-zidan-auto-uploadbooleantrueStart uploading as soon as files are picked.
showFileMetadata-zidan-show-file-metabooleantrueName + size line per file.
showPreview / previewdata-zidan-previewbooleantrueAvatar preview for images.
replaceTitle—stringChange imageAvatar title once a preview exists.
progressTemplate—stringUploading {percent}%Progress text template.
uploadedLabel—stringUploadedPer-file success text.
failedLabel—stringUpload failedPer-file error prefix.
canceledLabel—stringUpload canceledPer-file canceled text.
cancelLabel / retryLabel—stringCancel / RetryPer-file action labels.
renderFile—function—(itemElement, { file, index, state, field }) after the default row renders.

Every file option in one object

const upload = zidanField('#files', {
  /* Target by ID, class or element; no data-* attribute required */

  /* Variant & copy */
  variant: 'dropzone',              // dropzone | button | avatar | gallery | compact
  uploadIcon: 'upload',             // any registered icon name or SVG markup
  title: 'Choose a file',
  dropHint: 'Drag & drop or browse',
  layout: 'stacked',                // stacked | inline | compact | floating | outlined | card
  theme: 'default',
  framework: 'none',
  label: 'Attachments',
  hint: 'PDF or images up to 5 MB.',

  /* Rules */
  accept: 'image/*,.pdf',           // shown in the hint, checked against the picker
  maxFiles: 4,
  maxSizeMB: 5,                     // or maxSize: 5242880 (bytes)
  showFileMeta: true,
  showPreview: true,
  replaceTitle: 'Change image',

  /* Upload pipeline */
  // upload: function (file, context) { … }, // custom uploader, contract below
  // uploadUrl: '/api/files',                // or XHR endpoint
  uploadField: 'file',
  // uploadData: function (file, field) { return { folder: 'avatars' }; },
  // uploadHeaders: function (file, field) { return { 'X-Token': '…' }; },
  withCredentials: false,
  autoUpload: true,
  simulateUpload: false,            // visual-only pipeline
  simulateDuration: 900,            // ms

  /* Per-file UI */
  progressTemplate: 'Uploading {percent}%',
  uploadedLabel: 'Uploaded',
  failedLabel: 'Upload failed',
  canceledLabel: 'Upload canceled',
  cancelLabel: 'Cancel',
  retryLabel: 'Retry',
  // renderFile: function (itemElement, state) { … },

  /* Callbacks — also zidan:upload-start/progress/success/error/cancel */
  onUploadStart: function (event) { console.log('start', event.file); },
  onUploadProgress: function (event) { console.log(event.progress); },
  onUploadSuccess: function (event) { console.log('done', event.result); },
  onUploadError: function (event) { console.log('failed', event.error); },
  onUploadCancel: function (event) { console.log('canceled', event.file); }
});

Custom uploader contract:

zidanField('#files', {
  upload(file, context) {
    // file: the File being uploaded
    // context: { file, field, formData, signal, onProgress, complete, fail }
    const xhr = new XMLHttpRequest();
    // ...or return a promise / call context.complete(result) / context.fail(error)
    context.onProgress(40);              // 0–99 while working
    fetch('/upload', { method: 'POST', body: context.formData, signal: context.signal })
      .then(res => res.ok ? res.json() : Promise.reject(res.status))
      .then(data => context.complete(data))
      .catch(err => context.fail(err));
  }
});

Methods: getFiles(), getUploadState() ([{ file, name, size, status, progress, error, result }]), addFiles(files), replaceFiles(files), removeFile(fileNameOrIndex), clear(), setVariant(name), setUploader(fnOrUrl), uploadAll(), uploadFile(file), cancelUpload(file), cancelAll(), retryUpload(file).

Events: zidan:upload-start { file, name, size }, zidan:upload-progress { file, name, progress }, zidan:upload-success { file, name, result }, zidan:upload-error { file, name, error, message }, zidan:upload-cancel { file, name }, plus the shared zidan:change, zidan:remove ({ file, index }) and zidan:clear.

Callbacks: onUploadStart, onUploadProgress, onUploadSuccess / onUpload, onUploadError, onUploadCancel.

Select options

ZidanSelect keeps its full 1.x option set.

Core

OptionData attributeDefaultDescription
modedata-zidan-select, data-zidan-modeselectselect, combobox, tags.
layoutdata-zidan-layoutclassic-cleanFive select layouts (see theming doc).
themeFrameworkdata-zidan-frameworkautoauto, none, vanilla, bootstrap, tailwind, bulma, foundation.
themedata-zidan-themedefaultColour preset.
id—generatedRoot id prefix.
namedata-zidan-namenative nameName for hidden mirror input in mount mode.
disableddata-zidan-disablednativeMirrors the native disabled.
required—nativeMirrors native required.
validationdata-zidan-validationnullvalid \invalid.
scrollbardata-zidan-scrollbardefaultdefault, thin, fancy, hover, hidden.
customClasses—{}Map of root/control/input → class names.

Data

OptionData attributeDescription
options—Array of strings or {value,label,disabled,group}.
suggestions—Tags suggestions.
value—Initial value(s).
labeldata-zidan-labelFloating label text. An author <label> for the same control is hidden while the field is enhanced and restored by destroy().
ariaLabel—Accessible name for the generated combobox input; defaults to label.
placeholderdata-zidan-placeholderTrigger placeholder.

Behaviour

OptionData attributeDefaultDescription
multipledata-zidan-multiplefrom multipleMulti-select.
searchabledata-zidan-searchabletrue except plain selectType-to-filter. With searchable: false in select mode the text field is readOnly, so typing can never filter or hide the list — open it with a click, Space, Enter or ↓.
clearabledata-zidan-clearablefalseClear button.
closeOnSelect—single: trueClose after choosing.
maxDropdownHeight—280Listbox max height in px.
noResultsText—No results foundEmpty search message.
emptyText—No optionsEmpty source message.
loadingText—Searching…Async loading message.
clearText—Clear selectionClear button label.

Combobox / async

OptionDefaultDescription
fetchOptions(query, signal, context)—Return an array of items, or a page { items, hasMore } (or { items, total }). signal aborts stale requests; context is { page, pageSize, append, instance }.
fetchPageSize0Page size handed to fetchOptions. 0 keeps the legacy single-request behaviour.
fetchUrlnullDeclarative AJAX. GET this URL and the select builds its own fetchOptions — no JavaScript needed. Attribute: data-zidan-fetch-url.
fetchQueryParam'q'Query-string parameter that receives the search term ('' omits it).
fetchPageParam'page'1-based page number sent with every request ('' omits it).
fetchSkipParamnullSend skip = page × pageSize instead of fetchPageParam, for APIs that page by offset (dummyjson, Laravel, many REST APIs).
fetchPageSizeParam'limit'Parameter that receives fetchPageSize.
fetchItemsPathnullDot path to the array of rows in the JSON body (products, data.items). Without it the plugin looks for items, data, results, options, rows, products or records.
fetchTotalPathnullDot path to the total row count; with fetchPageSize it decides hasMore. Falls back to a top-level total.
fetchHasMorePathnullDot path to a boolean instead of a count.
fetchMethod, fetchHeaders, fetchCredentials'GET', null, 'same-origin'Request tuning for fetchUrl (JavaScript only).
autoLoadMoretrueScrolling near the dropdown bottom fetches the next page automatically.
loadMoreTextLoad moreLabel of the footer button rendered while hasMore is true.
cacheResultstrueCache pages per query + page. Clear with select.clearCache().
onLoadMore—Called when a follow-up page starts loading: { page, query, instance }.
debounce250Async debounce in ms.
minChars0Characters before fetching.
allowFreeTexttags onlyAllow values not in the list.
searchValuestrueMatch against values as well as labels.

Remote results are not filtered again on the client, so a server that already applied the query is never double-filtered. Use renderOption for custom rows; keep values stable across pages so the merge can de-duplicate them.

const users = zidanSelect('#owner', {
  mode: 'combobox',
  fetchPageSize: 20,
  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('loaded page', page)
});

users.loadMore();                 // manual next page
users.hasMoreResults();           // boolean
users.getAsyncState();            // { query, page, hasMore, loading, fetchingMore, error }
users.refreshOptions();           // clears the cache and refetches page 0
users.clearCache();               // drop cached pages only

fetchOptions may also reject: an initial failure shows an error state and getAsyncState().error keeps the message; call refreshOptions() to retry. If an appended page fails, the rows already loaded stay visible and the footer shows the error; clicking it retries. Appended fetches emit zidan:load-more with { page, query }; failures emit the usual zidan:error.

The cache size is global: ZidanSelect.cacheLimit = 50 pages (least-recently-used eviction).

AJAX from markup only

One URL is enough to turn a combobox into a remote search. The plugin sends the query, page and page size, reads the rows out of the JSON, and keeps every other behaviour (debounce, abort, cache, load-more, errors) identical to a hand-written fetchOptions.

<select id="product" name="product"
        data-zidan-select="combobox"
        data-zidan-fetch-url="/api/products/search"
        data-zidan-fetch-items-path="data.items"
        data-zidan-fetch-total-path="data.total"
        data-zidan-fetch-skip-param="skip"
        data-zidan-fetch-page-size="20">
</select>

That markup calls GET /api/products/search?q=…&limit=20&skip=0, then skip=20 for the next page, and stops when skip + limit >= data.total. Rows map automatically: value / label, or id / slug / code for the value and name / title / full_name for the label. A live page with both modes, against a real API and a static JSON file, ships as ajax.html.

Tags

OptionData attributeDefault
maxTagsdata-zidan-max-tagsInfinity
minTagLengthdata-zidan-min-tag-length1
maxTagLengthdata-zidan-max-tag-lengthInfinity
caseSensitivedata-zidan-case-sensitivefalse
allowFreeTextdata-zidan-allow-free-texttrue
delimiters—[',']
commitOnTab / commitOnBlur—false
valueDelimiter—,

With allowFreeText: false a tag you type must match an option or a suggestions entry by value or label (caseSensitive respected). Anything else is rejected: no tag is added and the control shows "…" is not in the list. through the tag error slot. Leave the option at its true default for free-form tags.

Rendering hooks

OptionSignature
filterOption(item, query)return boolean
renderOption(item, context)HTML string or element; context is { index, selected, active, query, instance }.
renderSelected(item, context)HTML string or element; context is { index, instance }.
renderTag(item, context)HTML string or element; context is { index, instance, disabled }.
validateTag(tag, tags, context)boolean or message string; tag is the formatted string, tags is the current tag list.
formatTag(tag, context)display string; context is { instance, tags }.

Select callbacks

CallbackPayload
onInit{ instance, mode, value }
onChange{ instance, value, previousValue? }
onSelect{ instance, value, item }
onOpen / onClose{ instance }
onTagAdd{ instance, tag, value }
onTagRemove{ instance, tag, value }
onLoadMore{ instance, page, query }
onError{ instance, message, error?, callback? }

Every callback receives a single payload object.

Every select option in one object

Copy the block, delete what you do not need. Values shown are the defaults; only clauses that change the shape of the result (options, value, callbacks) are commented out.

const picker = zidanSelect('#mymov', {
  /* Core */
  mode: 'combobox',                 // 'select' | 'combobox' | 'tags' (default 'select')
  layout: 'classic-clean',          // 5 select layouts, see theming.md
  themeFramework: 'none',           // 'auto' | 'none' | 'vanilla' | 'bootstrap' | 'tailwind' | 'bulma' | 'foundation'
  theme: 'default',                 // 'default' | 'modern' | 'minimal' | 'dark' | 'glass'
  // id: 'mymov',                   // root id prefix; leave unset for class targets
  // name: 'movie',                 // defaults to the native name
  disabled: false,
  required: false,
  validation: null,                 // 'valid' | 'invalid' | null
  scrollbar: 'default',             // 'default' | 'thin' | 'fancy' | 'hover' | 'hidden'
  customClasses: { root: '', control: '', input: '' },

  /* Data — omit to use the native <option>s */
  // options: [
  //   { value: 'inception', label: 'Inception' },
  //   { value: 'dune', label: 'Dune', group: 'Villeneuve' },
  //   { value: 'arrival', label: 'Arrival', disabled: true }
  // ],
  // suggestions: ['Interstellar', 'Oppenheimer'],
  // value: 'inception',            // string, or array for multiple/tags
  label: 'Movie',
  ariaLabel: 'Choose a movie',
  placeholder: 'Search a movie…',

  /* Behaviour */
  multiple: false,                  // mirrors native multiple by default
  searchable: true,                 // false in plain 'select' mode
  clearable: true,
  closeOnSelect: true,              // single mode
  maxDropdownHeight: 280,           // px
  noResultsText: 'No results found',
  emptyText: 'No options',
  loadingText: 'Searching…',
  clearText: 'Clear selection',

  /* Combobox / async */
  // fetchOptions: function (query, signal, context) {
  //   return fetch('/api/movies?q=' + encodeURIComponent(query) + '&page=' + context.page, { signal: signal })
  //     .then(function (response) { return response.json(); }); // items[] or { items, hasMore }
  // },
  fetchPageSize: 0,                 // >0 enables paged responses, load-more and scroll auto-load
  fetchUrl: null,                   // declarative AJAX endpoint; no fetchOptions needed
  fetchQueryParam: 'q',             // '' omits the search parameter
  fetchPageParam: 'page',           // 1-based; '' omits it
  fetchSkipParam: null,             // e.g. 'skip' sends page × fetchPageSize
  fetchPageSizeParam: 'limit',      // '' omits the page-size parameter
  fetchItemsPath: null,             // e.g. 'data.items'; common array names are auto-detected
  fetchTotalPath: null,             // row count used to calculate hasMore
  fetchHasMorePath: null,           // boolean path used instead of a total
  fetchMethod: 'GET',
  fetchHeaders: null,               // e.g. { Authorization: 'Bearer …' }
  fetchCredentials: 'same-origin',  // 'omit' | 'same-origin' | 'include'
  autoLoadMore: true,
  cacheResults: true,               // ZidanSelect.cacheLimit = 50 pages, LRU
  loadMoreText: 'Load more',
  debounce: 250,                    // ms
  minChars: 0,
  searchValues: true,               // match labels and values

  /* Tags (mode: 'tags') */
  maxTags: Infinity,
  minTagLength: 1,
  maxTagLength: Infinity,
  caseSensitive: false,
  allowFreeText: true,
  delimiters: [','],
  commitOnTab: false,
  commitOnBlur: false,
  valueDelimiter: ',',

  /* Rendering hooks */
  // filterOption: function (item, query) { return item.label.toLowerCase().includes(query.toLowerCase()); },
  // renderOption: function (item, context) {
  //   return (context.selected ? '✓ ' : '') + item.label;
  // },
  // renderSelected: function (item, context) { return '◉ ' + item.label; },
  // renderTag: function (item, context) { return String(item.label).toUpperCase(); },
  // validateTag: function (tag, tags, context) { return tag.length <= 24 || 'Use 24 characters or fewer'; },
  // formatTag: function (tag, context) { return tag.toUpperCase(); },

  /* Callbacks */
  onInit: function (event) { console.log('init', event.instance); },
  onChange: function (event) { console.log('value', event.value); },
  // onSelect: function (event) { console.log('selected', event.item); },
  // onOpen: function (event) { console.log('opened', event.instance); },
  // onClose: function (event) { console.log('closed', event.instance); },
  // onTagAdd: function (event) { console.log('tag added', event.tag); },
  // onTagRemove: function (event) { console.log('tag removed', event.tag); },
  // onLoadMore: function (event) { console.log('loading page', event.page); },
  // onError: function (event) { console.log('error', event.message); }
});

Methods for paged data: loadMore(), hasMoreResults(), getAsyncState(), refreshOptions(), clearCache().

Data attributes remain available as a 1:1 fallback; the tables above list the matching data-zidan-* name for each option, and data-zidan-options accepts any literal-value subset as JSON.

DOM data attributes

data-zidan-select, data-zidan-mode, data-zidan-layout, data-zidan-framework, data-zidan-theme, data-zidan-placeholder, data-zidan-label, data-zidan-name, data-zidan-multiple, data-zidan-searchable, data-zidan-clearable, data-zidan-disabled, data-zidan-allow-free-text, data-zidan-max-tags, data-zidan-min-tag-length, data-zidan-max-tag-length, data-zidan-case-sensitive, data-zidan-validation, data-zidan-scrollbar, data-zidan-fetch-url, data-zidan-fetch-method, data-zidan-fetch-query-param, data-zidan-fetch-page-param, data-zidan-fetch-skip-param, data-zidan-fetch-page-size, data-zidan-fetch-page-size-param, data-zidan-fetch-items-path, data-zidan-fetch-total-path, data-zidan-fetch-has-more-path, and the JSON escape hatch data-zidan-options (any JS option that takes a literal value). Marker classes: zidan-select, zidan-field, zidan-form.

Defaults

ZidanForm.themes          // ['default','modern','minimal','dark','glass']
ZidanForm.frameworks      // ['auto','none','vanilla','bootstrap','tailwind','bulma','foundation']
ZidanForm.fieldLayouts    // ['stacked','inline','card','compact','floating','outlined']
ZidanForm.variants        // { checkbox, switch, radio, file, range } accepted names
ZidanForm.stepperModes    // ['stacked','split','inline']
ZidanForm.phoneFormats    // ['national','international','e164']
ZidanForm.phoneCountries  // { US: { dial, mask, groups, min, max }, … }
ZidanForm.icons           // live icon registry (name → SVG markup)
ZidanForm.messages        // default validation messages
ZidanSelect.layouts       // five select layouts
ZidanSelect.scrollbars    // ['default','thin','fancy','hover','hidden']

themes and fieldLayouts are live arrays, so ZidanForm.themes.push('brand') registers a custom preset that theme / setTheme() will accept (register before initialising fields).

grid is not a field layout value: add class="zs-form-grid" to the wrapper (and zs-full to any field that should span the row) rather than putting it on a single field.

Instance methods

Fields

MethodDescription
getValue()Text/textarea value, checked value, radio value or selected files.
setValue(v)Writes to the native control and re-renders.
update() / refresh()Re-read native state (checked, disabled, validity, value).
validationTargets()Native element(s) whose constraints are mirrored.
`setValidation('valid'\'invalid'\null)`Mirrors state to classes and aria-invalid. A public 'invalid' call survives update() / refresh() and internal mirrors; user input/change/blur, value helpers that dispatch change, a non-empty select value, or another public state call clears/replaces it.
getValidation()Current validation state.
setError(message) / clearError()Set or clear the rendered error and invalid state.
checkAsync()Promise resolving to the custom-rule result; runs pending state and stale guards.
validate()Promise resolving to overall validity after native and custom rules.
isPending()Whether an async rule is currently running.
setTheme(name), setFramework(name), setLayout(name)Scoped restyling.
destroy()Restores the original DOM and removes every listener.

Checkbox adds setIndeterminate(bool), setChecked(bool) and isChecked().

Text inputs add stepUp(times?), stepDown(times?), setStepper(bool), getPhoneCountry(), setPhoneCountry(iso), setPhoneFormat(format), formatPhone(value?) and openPicker() / showPicker().

File adds getFiles(), getUploadState(), addFiles(), replaceFiles(), removeFile(), clear(), setVariant(), setUploader(), uploadAll(), uploadFile(), cancelUpload(), cancelAll() and retryUpload().

Select

open(), close(), toggle(), isOpen(), getValue(), setValue(), clear(), setOptions(items), addTag(), removeTag(), getTags(), enable(), disable(), setLayout(), setFramework(), setScrollbar(), setValidation(), refresh(), loadMore(), hasMoreResults(), getAsyncState(), refreshOptions(), clearCache(), on(event, handler), off(event, handler), announce(message), destroy().

Events

EventDetail
zidan:init`{ instance, kind \mode, ... }`
zidan:change{ instance, value, previousValue? }, { checked }, { files }
zidan:input{ instance, value } (text/range)
zidan:validation{ instance, state, message? }
zidan:async-validation{ instance, valid, message, error? }
zidan:open / zidan:close{ instance } (select)
zidan:select{ instance, value, item } (select)
zidan:no-results{ instance, query } (select)
zidan:tag-add / zidan:tag-remove{ instance, tag, value } (select tags)
zidan:load-more{ instance, page, query } (select pagination)
zidan:reveal{ instance, visible } (password)
zidan:remove{ instance, file, index? } (file upload)
zidan:step{ instance, value, direction, step } (number stepper)
zidan:phone-country{ instance, country }
zidan:phone-format{ instance, format }
zidan:icon-click{ instance, icon, position }
zidan:picker{ instance, type }
zidan:upload-start{ instance, file, name, size }
zidan:upload-progress{ instance, file, name, progress }
zidan:upload-success{ instance, file, name, result }
zidan:upload-error{ instance, file, name, error, message }
zidan:upload-cancel{ instance, file, name }
zidan:clear{ instance }
zidan:destroy{ instance }
zidan:error{ error, callback, instance }

Markdown source: docs/options.md. Generated by scripts/docs.mjs — edit the Markdown, not this page.