5

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)]
Chris Murphy
  • 6,411
  • 1
  • 24
  • 42
Kingfranz
  • 184
  • 1
  • 12
  • You don't have to embed. One thing you might have missed is the `cljs->js` macro, also known as `#js`. – Chris Murphy Jul 05 '17 at 17:46
  • @Kingfranz 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. – Scott Jul 05 '17 at 20:00
  • Yes, this is "real" server-side Hiccup :-) – Kingfranz Jul 05 '17 at 21:08
  • The clj->js sound interesting but it seems to be more for defining data than to set properties in elements. – Kingfranz Jul 05 '17 at 21:11

2 Answers2

2

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)]
Aleph Aleph
  • 5,215
  • 2
  • 13
  • 28
0

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))]
Kingfranz
  • 184
  • 1
  • 12