Hotwire Discussion

Turbo - Checkboxes in GET Forms not submitted when unchecked

Hi everyone,

I’m getting started with Stimulus/Turbo and trying to use it to filter out data on a page via a Form using GET.

  1. When using checkboxes, an “off” value is not sent to the url. So if I turn the checkbox on, then I can’t turn it off on form submit because the request will now always have ?showCompleted=1

    I think this is due to the FormData object not having the value available, so when the request is pre-processed by Turbo, the url is merged with FormData, and it just keeps the old one.

    I’ve gotten around it by adding a <input type="hidden" value="0" name="showCompleted"> when it is checked off via a Stimulus controller, but I was wondering if there was a better solution?

  2. The preview loads the original checkbox on/off state, then changes it to the new one. It looks odd as you see the checkbox change.

    I can disable the preview, but is there a recommended way to handle this case?

Thanks!

1. Form not sending an “off” checkbox

This is the W3C HTML 4 Form standard:

Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is “on” when the control element’s checked attribute is set. When a form is submitted, only “on” checkbox controls can become successful.

You could

  • assume a default on the backend if form does not past checkbox parameter (standard)
  • use 2 radio buttons with 2 values (standard)
  • stay with the hidden field workaround you implemented (non-standard)

2. FOPC (Flash of Preview Content)

Assuming the FOPC occurs on a “new” form, turbo no-preview is an appropriate solution.

Hi @tleish,

Thanks for the detailed response!

1. Form not sending an “off” checkbox

The checkbox part using a default makes sense. My issue is I can’t “uncheck” it with Turbo working.

You can check out a video here: Uncheck not working

In short:

 1. Go to page: url is: https://localhost:8000/example
 2. Check, Submit:  url is https://localhost:8000/example?showCompleted=1
 3. Un-check, Submit: url is https://localhost:8000/example?showCompleted=1

2. FOPC (Flash of Preview Content)

That makes sense. Thinking about it, I can’t predict what the user will check/uncheck, so it doesn’t make sense to have a preview.