Core

Forms without a forms library

An input already holds its own value, so mx adds no form layer. Read values on submit, or mirror every keystroke when you need to reshape them. Every pattern below is plain mx you can copy, and most come with a live result.

Key ideas

  • One oninput on the <form> hears every field. Events bubble, so there's no per-input wiring.
  • There is no controlled / uncontrolled split. Bind a value only when you need it mid-typing.
  • Validate on submit, or per field on blur, then re-validate on input once an error shows.
  • Re-render the whole form when state changes. The reconciler reuses the nodes, so focus and typed text survive.

One oninput for the form#

For basic UX, a single oninput on the form (event delegation) is all you need. e.target.name tells you which field changed.

JSRunnablePlayground
let { form, label, input, button, p } = mx;

let name = '', email = '';
let host = dom.div();

function update() {
    host.render(
        form({
            // One listener on the form hears every field: input events bubble.
            oninput(e) {
                if (e.target.name === 'name') name = e.target.value;
                if (e.target.name === 'email') email = e.target.value;
                update();
            },
            onsubmit(e) {
                e.preventDefault();
                alert('Submitting: ' + JSON.stringify({ name, email }));
            }
        },
            label('Name', input({ name: 'name', type: 'text', '.value': name })),
            label('Email', input({ name: 'email', type: 'email', '.value': email })),
            button({ type: 'submit' }, 'Submit'),
            name ? p('Hello, ' + name + (email ? ' (' + email + ')' : '')) : null
        )
    );
}

update();
document.body.render(host);

If the UI changes with the input (a mode that reveals different fields), re-render the section or container when state changes. mx updates minimally. See conditional fields.

Controlled vs uncontrolled#

React draws a hard line between controlled inputs (React owns the value, every keystroke flows through state) and uncontrolled ones (the DOM owns the value, you read it with a ref). mx has no such concept, because the DOM already does it. An <input> holds its own value whether or not you touch it. You decide how involved you want to be:

JS
// "Controlled" style: the DOM mirrors a variable on every render.
// Set .value each time and re-render on input. You always hold the
// value, so you can transform it (uppercase, mask, clamp) before it shows.
let value = '';
function render() {
    host.render(
        input({ 'aria-label': 'Uppercase text', '.value': value,
            oninput(e) { value = e.target.value.toUpperCase(); render(); } })
    );
}

// "Uncontrolled" style: the DOM owns the value. Don't set .value,
// don't re-render on input. Read it only when you need it.
host.render(
    form({ onsubmit(e) {
        e.preventDefault();
        let data = new FormData(e.currentTarget);   // read on submit
        save(Object.fromEntries(data));
    }},
        input({ name: 'title', 'aria-label': 'Title' }),    // no .value, no oninput - it just works
        button({ type: 'submit' }, 'Save')
    )
);
Controlled styleUncontrolled style
You write.value + oninput + re-renderNothing but name
Source of truthYour variableThe DOM element
Read the valueIt's already in your variableFormData / el.value on submit
Use whenYou transform or validate as the user typesYou only need the value at submit
Default to uncontrolled

If you don't need the value mid-typing, don't bind it. Skipping .value and oninput means no per-keystroke re-render and less code: the form just works and you read it once on submit (the validation-on-submit example does exactly this). Reach for the controlled style only when you need to see or reshape every keystroke.

Reshaping while typing moves the caret

When you transform the value on every keystroke (uppercase, mask, clamp) and write it back via .value, the cursor jumps to the end of the field, because setting .value resets the caret. For a trailing-edit field nobody notices, but for editing mid-string it's maddening. Either transform on blur instead of oninput, or capture and restore the caret around the re-render:

JSFragment
oninput(e) {
    let pos = e.target.selectionStart;        // remember caret
    value = e.target.value.toUpperCase();
    render();
    e.target.setSelectionRange(pos, pos);     // restore it after .value reset
}

Validate on submit#

From a UX perspective, validating on submit is often simpler and less noisy. Nothing is bound: FormData reads the fields once, and a failed check re-renders the form with an errors map.

JSRunnablePlayground
let { form, label, input, small, button, div } = mx;
let prefix = 'login-' + crypto.randomUUID();
function loginForm(errors = {}) {
    function field(name, text, type) {
        return div(
            label({ for: prefix + name }, text),
            input({ id: prefix + name, name, type,
                'aria-invalid': String(!!errors[name]),
                'aria-describedby': prefix + name + '-error' }),
            small({ id: prefix + name + '-error', class: 'error' }, errors[name] || '')
        );
    }
    return form({
        novalidate: true,
        onsubmit(e) {
            e.preventDefault();
            let data = new FormData(e.currentTarget);
            let user = (data.get('user') || '').trim();
            let pass = data.get('pass') || ''; // Passwords are never trimmed.
            let errors = {};
            if (!user) errors.user = 'Enter your username.';
            if (!pass) errors.pass = 'Enter your password.';
            container.render(loginForm(errors));
            if (!Object.keys(errors).length) return alert('Logged in!');
            // Focus the first invalid field; a screen reader announces its error.
            container.querySelector('[aria-invalid=true]').focus();
        }
    },
        // Stable field wrappers and error slots preserve uncontrolled input nodes.
        field('user', 'Username', 'text'),
        field('pass', 'Password', 'password'),
        button({ type: 'submit' }, 'Login')
    );
}
let container = dom.div();
container.render(loginForm());
document.body.render(container);
Why the typed text survives the error re-render

Each field keeps the same wrapper and an always-present error slot, so the re-render lands on the same nodes in the same positions. The reconciler never replaces an <input> it can reuse, and because no .value is in the description it never touches what the user typed. Passwords are read as-is: never trim() a password.

Field-level validation#

Validating on submit (above) is form-level, with one check for everything at once. Field-level validation gives feedback per field, typically on blur (when the field loses focus), so you're not flagging an email as invalid while the user is still on the first character. Keep an errors map keyed by field name and re-render the form. The reconciler only touches the field whose error changed:

  1. TypingNo error yet. Don't nag mid-entry.
  2. BlurValidate the field that lost focus.
  3. InputOnce it shows an error, re-check every keystroke.
  4. SubmitValidate every field, regardless.
JSRunnablePlayground
let { form, label, input, small, button, div } = mx;

let prefix = 'field-' + crypto.randomUUID();
let values = { email: '', age: '' };
let errors = {};
let host = dom.div();

let validators = {
    email: v => /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v) ? '' : 'Enter an email like name@example.com.',
    age:   v => +v >= 18 ? '' : 'Enter an age of 18 or over.'
};

function validateField(name) {
    errors[name] = validators[name](values[name]);
    render();
}

function field(name, labelText, type) {
    return div(
        label({ for: prefix + name }, labelText),
        input({ id: prefix + name, 'aria-describedby': prefix + name + '-error', name, type, '.value': values[name],
            // re-validate while typing only AFTER the first error is shown -
            // don't nag the user mid-entry
            oninput(e) { values[name] = e.target.value; if (errors[name]) validateField(name); },
            onblur() { validateField(name); },           // validate when the field loses focus
            'aria-invalid': errors[name] ? 'true' : 'false'
        }),
        small({ id: prefix + name + '-error', class: 'error' }, errors[name] || '')
    );
}

function render() {
    host.render(
        form({ novalidate: true, onsubmit(e) {
            e.preventDefault();
            Object.keys(validators).forEach(validateField);   // validate ALL on submit
            if (Object.values(errors).every(msg => !msg)) alert('Submitted!');
            else host.querySelector('[aria-invalid=true]').focus(); // announces its error
        }},
            field('email', 'Email', 'email'),
            field('age', 'Age', 'number'),
            button({ type: 'submit' }, 'Create account')
        )
    );
}

render();
document.body.render(host);
Validate on blur, re-validate on input

The pattern that feels best is to validate a field when it loses focus and then, once it's showing an error, re-validate on every keystroke so the error clears the instant it's fixed. The if (errors[name]) guard in oninput is what gives you that "don't nag early, but forgive immediately" behavior. On submit, validate everything regardless.

Debounced input#

Some input handlers are expensive, such as a search query, a filter over thousands of rows or a network request. Running them on every keystroke is wasteful. Debouncing waits until typing pauses, then runs once. It's a four-line helper and needs no library:

JSRunnablePlayground
let { input, ul, li, p } = mx;

// Run fn only after input pauses for ms - one search per pause,
// not one per keystroke
function debounce(fn, ms) {
    let timer;
    return (...args) => {
        clearTimeout(timer);
        timer = setTimeout(_ => fn(...args), ms);
    };
}

let FRUITS = ['apple', 'apricot', 'banana', 'blueberry', 'cherry', 'grape', 'mango', 'melon', 'orange', 'peach'];
let results = [];
let runs = 0;
let host = dom.div();

let search = debounce(query => {
    results = query ? FRUITS.filter(f => f.includes(query.toLowerCase())) : [];
    runs++;
    render();
}, 250);

function render() {
    host.render(
        input({ 'aria-label': 'Filter fruit', type: 'search', placeholder: 'Filter fruit...',
            oninput(e) { search(e.target.value); } }),
        results.length ? ul(...results.map(r => li(r))) : null,
        p('Searches actually run: ' + runs)
    );
}

render();
document.body.render(host);
Watch the counter

Type quickly and the "searches actually run" counter ticks once per pause, not once per keystroke. The same debounce helper wraps any handler, for example on resize, scroll or autosave. For the inverse (run immediately, then ignore until quiet) the shape is the same with a leading-edge flag.

Async validation#

Debounce request launch, but invalidate the previous result and abort its request immediately on every input. A generation guard also rejects work already queued when cancellation occurs. This example needs the endpoint described in its first comment, but the demo uses a local transport fixture. Try admin, root or alice.

  1. ++generationOlder results are now stale
  2. abort()Cancel the request in flight
  3. setTimeoutLaunch after 350 ms of quiet
  4. Generation checkOnly the latest result may render
JS
// Integration: GET /api/username-free?name=... returns { free: boolean }.
let { label, input, p } = mx;
let status = 'idle';
let controller, timer;
let generation = 0;
let host = dom.form({ novalidate: true, onsubmit: e => e.preventDefault() });
let id = 'username-' + crypto.randomUUID();
let MESSAGES = { checking: 'Checking...', available: 'Available', taken: 'Already taken', error: 'Check failed; edit to retry' };
function check(name) {
    let mine = ++generation; // Invalidate NOW, not after the debounce delay.
    clearTimeout(timer);
    controller?.abort();
    status = name ? 'checking' : 'idle';
    render();
    if (!name) return;
    timer = setTimeout(async _ => {
        controller = new AbortController();
        try {
            let response = await fetch('/api/username-free?name=' + encodeURIComponent(name),
                { signal: controller.signal });
            if (!response.ok) throw new Error('Username check failed');
            let data = await response.json();
            if (mine !== generation) return;
            status = data.free ? 'available' : 'taken';
        } catch (error) {
            if (mine !== generation || error.name === 'AbortError') return;
            status = 'error';
        }
        render();
    }, 350);
}
// The owner calls dispose() before removing this form.
function dispose() { ++generation; clearTimeout(timer); controller?.abort(); }
function render() {
    host.render(
        label({ for: id }, 'Username'),
        input({ id, name: 'username', type: 'text',
            'aria-describedby': id + '-status',
            'aria-invalid': String(status === 'taken'),
            oninput(e) { check(e.target.value.trim()); } }),
        p({ id: id + '-status', role: 'status' }, MESSAGES[status] || '')
    );
}
render();
document.body.render(host);
Cancellation and ownership

Abort reduces unnecessary work, and the generation check prevents stale completions from changing the UI. Keep both. The owner must call dispose() before removing this form to cancel timers and pending work (see Lifecycle). HTTP failures get a separate retryable error state.

Conditional fields#

Sometimes changing a select should switch the whole form. Keep a tiny state variable and re-render:

JSRunnablePlayground
let { form, label, select, option, input, button, div } = mx;

let prefix = 'contact-' + crypto.randomUUID();
let mode = 'email'; // 'email' | 'phone'

function contactForm() {
    return form({
        oninput(e) {
            if (e.target.name === 'mode') {
                mode = e.target.value;
                host.render(contactForm()); // re-render form
            }
        },
        onsubmit(e) { e.preventDefault(); alert('OK'); }
    },
        label({ for: prefix + 'mode' }, 'Preferred contact'),
        select({ id: prefix + 'mode', name: 'mode', '.value': mode },
            option({ value: 'email' }, 'Email'),
            option({ value: 'phone' }, 'Phone')
        ),
        mode === 'email'
            // The reconciler reuses the same <input> node across the switch (same tag,
            // same position), so set .value explicitly or the typed text carries over.
            ? div(label({ for: prefix + 'email' }, 'Email'), input({ id: prefix + 'email', type: 'email', name: 'email', '.value': '' }))
            : div(label({ for: prefix + 'phone' }, 'Phone'), input({ id: prefix + 'phone', type: 'tel', name: 'phone', '.value': '' })),
        button({ type: 'submit' }, 'Save')
    );
}

let host = dom.div();
host.render(contactForm());
document.body.render(host);
Why the explicit .value: '' reset

The reconciler matches children by tag and position, so the email field's <input> and the phone field's <input> are the same node reused across the switch. Only its attributes (type, name, id) change. Its DOM value (what the user typed) isn't in the description, so the reconciler never touches it, and the text would carry over into the other field. Setting .value: '' clears the reused node on switch. (If you wanted to keep a value per mode, you'd set .value to that mode's stored string instead.)

Checkboxes & radios#

Checkboxes and radios use the .checked property for state. Group radios with the same name, and wrap each group in a <fieldset> with a <legend> so the question is announced with every option.

JSRunnablePlayground
let { form, fieldset, legend, label, input, button } = mx;

let agreed = false;
let payment = 'credit';

function agreementForm() {
    return form({
        oninput(e) {
            if (e.target.name === 'agree') agreed = e.target.checked;
            if (e.target.name === 'payment') payment = e.target.value;
            demo.render(agreementForm());
        },
        onsubmit(e) {
            e.preventDefault();
            alert('Agreed: ' + agreed + ', Payment: ' + payment);
        }
    },
        fieldset(legend('Terms agreement'),
            label(input({ type: 'checkbox', name: 'agree', '.checked': agreed }), ' I agree to the terms')
        ),
        // A fieldset + legend names the group, so a screen reader announces
        // "Payment method" before each option.
        fieldset(legend('Payment method'),
            label(input({ type: 'radio', name: 'payment', value: 'credit', '.checked': payment === 'credit' }), ' Credit card'),
            label(input({ type: 'radio', name: 'payment', value: 'paypal', '.checked': payment === 'paypal' }), ' PayPal')
        ),
        button({ type: 'submit' }, 'Continue')
    );
}

let demo = dom.div();
demo.render(agreementForm());
document.body.render(demo);

Select lists#

A <select> uses .value for the selected value and .selectedIndex for its index.

JSRunnablePlayground
let { form, label, select, option, button, p } = mx;

let prefix = 'country-' + crypto.randomUUID();
let country = 'us';

function countryForm() {
    return form({
        oninput(e) {
            if (e.target.name === 'country') {
                country = e.target.value;
                selectDemo.render(countryForm());
            }
        },
        onsubmit(e) {
            e.preventDefault();
            alert('Selected country: ' + country);
        }
    },
        label({ for: prefix }, 'Country'),
        select({ id: prefix, name: 'country', '.value': country },
            option({ value: 'us' }, 'United States'),
            option({ value: 'ca' }, 'Canada'),
            option({ value: 'uk' }, 'United Kingdom'),
            option({ value: 'de' }, 'Germany')
        ),
        p('Selected: ' + country.toUpperCase()),
        button({ type: 'submit' }, 'Submit')
    );
}

let selectDemo = dom.div();
selectDemo.render(countryForm());
document.body.render(selectDemo);

Multi-step wizard#

A multi-step form keeps all its data in one object and a step counter. Each step renders different fields, and the navigation buttons move between them. The wizard re-renders whenever the step changes.

JSRunnablePlayground
let { form, fieldset, legend, label, input, button, div, p } = mx;

let prefix = 'wizard-' + crypto.randomUUID();
let STEPS = ['Account', 'Plan', 'Confirm'];
let step = 0;
let data = { name: '', email: '', plan: 'free' };
let host = dom.div();

// One function per step; each returns that step's fields.
let views = [
    _ => [
        label({ for: prefix + 'name' }, 'Name'),
        input({ id: prefix + 'name', name: 'name', type: 'text', '.value': data.name }),
        label({ for: prefix + 'email' }, 'Email'),
        input({ id: prefix + 'email', name: 'email', type: 'email', '.value': data.email })
    ],
    _ => [
        label(input({ type: 'radio', name: 'plan', value: 'free', '.checked': data.plan === 'free' }), ' Free'),
        label(input({ type: 'radio', name: 'plan', value: 'pro', '.checked': data.plan === 'pro' }), ' Pro ($9/mo)')
    ],
    _ => [
        p('Name: ' + data.name),
        p('Email: ' + data.email),
        p('Plan: ' + data.plan)
    ]
];

function go(n) {
    step = n;
    host.render(wizard());
    // The old step's nodes are gone: move focus into the new step.
    (host.querySelector('fieldset input:checked') || host.querySelector('fieldset input') || host.querySelector('[type=submit]')).focus();
}

function wizard() {
    let last = step === STEPS.length - 1;
    return form({
        // Field names match the keys of data, so one handler serves every step.
        oninput(e) { data[e.target.name] = e.target.value; },
        // Continue is the submit button, so Enter advances too.
        onsubmit(e) {
            e.preventDefault();
            if (last) alert('Done! ' + JSON.stringify(data));
            else go(step + 1);
        }
    },
        fieldset(
            legend('Step ' + (step + 1) + ' of ' + STEPS.length + ': ' + STEPS[step]),
            ...views[step]()
        ),
        div(
            // Back is always rendered (hidden on step 1), so the reconciler
            // never turns it into the submit button mid-click.
            button({ type: 'button', hidden: step === 0, onclick() { go(step - 1); } }, 'Back'),
            button({ type: 'submit' }, last ? 'Submit' : 'Continue')
        )
    );
}

host.render(wizard());
document.body.render(host);
Wizard pattern

Keep all form data in one object and a step counter. Each step is a function that returns its fields, and the <legend> says where you are. Because every field's name matches a key of data, one delegated oninput records all of them, and Continue is the submit button, so Enter advances. The same pattern scales to any number of steps.