jkk / formative

Web forms for Clojure and ClojureScript - rendering, parsing, and validating
208 stars 18 forks source link

Why do you create a hidden input field for a checkbox? #38

Open Kungi opened 9 years ago

Kungi commented 9 years ago

When I try to render a checkbox I get an extra hidden input field. Is this necessary?

(form-core/render-form {:fields [{:name :some-nome :label "Some Label"  :type :checkbox}]
                        :values {}
                        :submit-label "Submit"})

[:div
 {:class "form-shell form-horizontal bootstrap-form"}
 nil
 [:form
  {:method "POST"}
  (()
   ([:fieldset
     {:class "fieldset-some-nome"}
     ([:div
       {:id "row-field-some-nome", :class "field-group  control-group checkbox-row"}
       ([:div {:class "empty-shell"} nil]
        [:div
         {:class "input-shell controls"}
         nil
         [:label.checkbox
          {:for "field-some-nome"}
          " "
          ((nil [:input {:value "false", :name "some-nome", :type "hidden"}])
           (nil [:input {:checked false, :value "true", :id "field-some-nome", :name "some-nome", :type "checkbox"}]))
          " "
          [:span.cb-label "Some Label"]]
         nil
         nil
         nil])])]
    [:fieldset
     {:class "fieldset-submit"}
     ([:div
       {:id "row-field-submit", :class "form-actions submit-group  control-group submit-row"}
       ([:div {:class "empty-shell"} nil]
        [:div
         {:class "input-shell"}
         nil
         (nil [:input {:value "Submit", :class " btn btn-primary", :id "field-submit", :name "submit", :type "submit"}])
         nil
         nil
         nil])])]))]]
iku000888 commented 7 years ago

@jkk Would be great if you could shed a bit of light on this. I can confirm that there is code that deliberately handles this, but not sure how all the pieces fit together yet (rendering/parsing).

jkk commented 7 years ago

Normally, when a checkbox input is unchecked, browsers do not include its name or value in the encoded post data when the form is submitted. The hidden input is a workaround to ensure there's always a name and value for the checkbox submitted. There may be other ways to handle this but that was a method I chose at the time.

iku000888 commented 7 years ago

Thanks for the really helpful insight on a subtle point! Thinking of keeping this open for now because I have a vague memory where this caused some unexpected behaviour that was somehow worked around.