Skip to main content

FormData won't pickup disabled form items and checkboxes don't have a readonly state

5/4/2021 ‚ÄĒ 2 min read

Consider a form which has a checkbox that the checked state is controlled by something else. Maybe a "Select/Deselect All" option. Here's a snippet where I've just hardcoded the value of the checkbox input.

  <form>
    <label for="is-chicken">ūüźĒ?</label>
     <input name="is-chicken" type="checkbox" checked disabled />
     <button type="submit">Submit</button>
  </form>

  <script>
    const form = document.querySelector('form')
  
    form.onsubmit = e => {
        e.preventDefault()
        const formData = new FormData(e.currentTarget)
        const isChicken = formData.get('is-chicken')
        console.log(isChicken) // null
    }
  </script>

Rendered HTML  - disabled

I want to make sure that I can block the user from interacting with the checkbox and yet still read the value.

Maybe readonly would work?

  <form>
    <label for="is-chicken">ūüźĒ?</label>
     <input name="is-chicken" type="checkbox" checked readonly />
     <button type="submit">Submit</button>
  </form>

  <script>

  const form = document.querySelector('form')

  form.onsubmit = e => {
      e.preventDefault()
      const formData = new FormData(e.currentTarget)
      const isChicken = formData.get('is-chicken')
      console.log(isChicken) // on
  }

  </script>

Rendered HTML - readonly

MDN says

The readonly attribute is supported by  text, search, url, tel, email, password, date, month, week, time, datetime-local, and number<input> types and the <textarea> form control elements. If present on any of these input types and elements, the :read-only pseudo class will match. If the attribute is not included, the :read-write pseudo class will match.

The attribute is not supported or relevant to <select> or input types that are already not mutable, such as checkbox and radio or cannot, by definition, start with a value, such as the file  input type. range and color, as both have default values. It is also not supported on hidden as it can not be expected that a user to fill out a form that is hidden. Nor is it supported on any of the button types, including image.

When up against this set of requirements, maybe there's a better away to solve the problem.

Read moreBack
© 2021 by Madole.
GitHub Repository
Last build: 1641535800708