Created
March 29, 2013 17:04
-
-
Save terjesb/5272131 to your computer and use it in GitHub Desktop.
How to get form data in a ClojureScript app, other than getting values separately? I have a page with many instances of the same form, and a button to submit each form. I couldn't find anything obvious in Domina, Enfocus or Dommy. Then I found goog.dom.forms.getFormDataMap, but the goog.structs.Map it returns doesn't seem to be directly usable f…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns form-data | |
(:require [clojure.string :as str] | |
[goog.dom :as gdom] | |
[goog.string :as gstring] | |
[goog.dom.forms :as gforms] | |
[domina :refer [by-class]] | |
[domina.events :as ev])) | |
;; form-decode from ring.util.codec | |
(defn assoc-conj | |
"Associate a key with a value in a map. If the key already exists in the map, | |
a vector of values is associated with the key." | |
[map key val] | |
(assoc map key | |
(if-let [cur (get map key)] | |
(if (vector? cur) | |
(conj cur val) | |
[cur val]) | |
val))) | |
(defn form-decode-str | |
"Decode the supplied www-form-urlencoded string." | |
[^String encoded] | |
(gstring/urlDecode encoded)) | |
(defn form-decode | |
"Decode the supplied www-form-urlencoded string. | |
If the encoded value is a string, a string is returned. | |
If the encoded value is a map of parameters, a map is returned." | |
[^String encoded] | |
(if-not (gstring/contains encoded "=") | |
(form-decode-str encoded) | |
(reduce | |
(fn [m param] | |
(if-let [[k v] (str/split param #"=" 2)] | |
(assoc-conj m (form-decode-str k) (form-decode-str v)) | |
m)) | |
{} | |
(str/split encoded #"&")))) | |
(defn form-data [form] | |
(form-decode (gforms/getFormDataString form))) | |
(defn parent-form [btn] | |
(gdom/getAncestorByTagNameAndClass btn "form")) | |
(defn btn-handler [evt] | |
(ev/prevent-default evt) | |
(let [btn (ev/current-target evt) | |
form (parent-form btn) | |
data (form-data form)] | |
(js/alert data))) | |
(defn ^:export init [] | |
(ev/listen! (by-class "btn-primary") :click btn-handler)) |
I wrapped your code here.
Depending on the browser support you might take a look at FormData which makes it really simple ...
https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is this still the best way to get the data from forms with cljs without using jquery? If so, I suggest to library it.