How do I embed javascript in clojure Hiccup?
Asked Answered
J

2

6

I'm writing a webserver app in clojure with Hiccup (and other things). I'm trying to have a check-box enable and disable two drop-down fields with a little JS but I can't make it work.

[:head
[:script "function toggleText(cb, t1, t2) {
    document.getElementById(t1).disabled = !cb.checked;
    document.getElementById(t2).disabled = !cb.checked;
}"]]

[:td (hf/check-box {:on-change (str "toggleText(" (name endtag) "," (name tytag) "," (name tmtag) ")")} endtag)]
[:td (hf/drop-down tytag (range 2013 2031) 2017)]
[:td (hf/drop-down tmtag (range 1 13) 6)]
Jockey answered 5/7, 2017 at 17:23 Comment(4)
You don't have to embed. One thing you might have missed is the cljs->js macro, also known as #js.Dewan
@Jockey could you clarify if you're using "real" Hiccup on the server-side in .clj files, or else Hiccup-style syntax client-side, using Reagent in .cljs files.Didymous
Yes, this is "real" server-side Hiccup :-)Jockey
The clj->js sound interesting but it seems to be more for defining data than to set properties in elements.Jockey
S
3

on-change is a React handler and won't work in server-side HTML.

If you don't want to create a separate JS file, you can use the onclick attribute: the below should work (provided that the hf/check-box function creates an element with the given properties):

[:td (hf/check-box
      {:onclick (str "toggleText(" (name endtag) ","
                     (name tytag) "," (name tmtag) ")")}
      endtag)]
Subadar answered 5/7, 2017 at 22:33 Comment(0)
J
1

Thanks Aleph, your fix together with adding getElementById for the cb parameter in the function did the trick!

The function now looks like this

[:script "function toggleText(cb, t1, t2) {
    document.getElementById(t1).disabled = !document.getElementById(cb).checked;
    document.getElementById(t2).disabled = !document.getElementById(cb).checked;}"]

And I simplified the Hiccup code too (not passing the tags as parameters) so it looks like this

[:td (hf/check-box {:onclick (str "toggleText('endtag','toyear','tomonth')")} :endtag (some? (:toyear m)))]
[:td (hf/drop-down :toyear (range 2013 2031))]
[:td (hf/drop-down :tomonth (range 1 13))]
Jockey answered 6/7, 2017 at 9:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.