Skip to content

pk-checkbox / pk-lightswitch form value doesn't update when toggled #1

Description

@chasegiunta

Package: @verbb/plugin-kit-web 2.0.20 (also on main)

Summary

pk-checkbox and pk-lightswitch don't update their form value when they're toggled after the first render. A native form submission or new FormData(form) keeps the value from the first render.

Steps to reproduce

<form id="f">
  <pk-checkbox name="agree" checkboxvalue="yes">Agree</pk-checkbox>
  <pk-lightswitch name="notify" value="1"></pk-lightswitch>
</form>
  1. Load the page (both unchecked), then click both to turn them on.
  2. Run [...new FormData(document.getElementById('f'))].

Expected: [['agree', 'yes'], ['notify', '1']]
Actual: []

It also happens the other way round: an element rendered with checked keeps submitting its value after being turned off.

Cause

PkFormAssociatedElement.updated() only calls syncFormValue() when value, disabled, required or name change:

if (changed.has('value') || changed.has('disabled') || changed.has('required') || changed.has('name')) {
    this.syncFormValue();
}

For pk-checkbox and pk-lightswitch, the submitted value depends on checked. Neither component's updated() override calls syncFormValue() when checked changes, so setFormValue() only runs on the first render.

Suggested fix

Call this.syncFormValue() when checked changes in both components (in updated(), or in the change handlers before dispatching change). Alternatively, make the base class watch checked too.

Workaround

We're re-syncing on change for now:

document.addEventListener('change', (e) => {
  const el = e.composedPath()[0];
  if (el?.localName === 'pk-checkbox' || el?.localName === 'pk-lightswitch') el.syncFormValue?.();
}, true);

Thanks for Plugin Kit, it's been great to build with.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions