Skip to content

Commit

Permalink
Allow multiple selected options in select elements
Browse files Browse the repository at this point in the history
Allow multiple selected options in order to support select elements that
have the 'multiple' attribute. The 'selected' argument can now be a
collection of values or a predicate function, as well as a single value.
  • Loading branch information
Xuan Wu committed Feb 9, 2024
1 parent 92f18b7 commit 3a46216
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
10 changes: 8 additions & 2 deletions src/hiccup/form.clj
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@
:value value
:checked checked?}]))

(defn- selected? [x selected]
(boolean (cond
(sequential? selected) ((set selected) x)
(ifn? selected) (selected x)
:else (= x selected))))

(defelem select-options
"Creates a seq of option tags from a collection."
([coll] (select-options coll nil))
Expand All @@ -83,8 +89,8 @@
(let [[text val] x]
(if (sequential? val)
[:optgroup {:label text} (select-options val selected)]
[:option {:value val :selected (= val selected)} text]))
[:option {:selected (= x selected)} x]))))
[:option {:value val :selected (selected? val selected)} text]))
[:option {:selected (selected? x selected)} x]))))

(defelem drop-down
"Creates a drop-down box using the `<select>` tag."
Expand Down
20 changes: 17 additions & 3 deletions test/hiccup/form_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,23 @@
"<option value=\"2\">baz</option></optgroup>")
(select-options [["Foo" [1 2]]] 2)
(str "<optgroup label=\"Foo\"><option>1</option>"
"<option selected=\"selected\">2</option></optgroup>")))


"<option selected=\"selected\">2</option></optgroup>")
(select-options ["foo" "bar" "baz"] ["foo" "bar"])
(str "<option selected=\"selected\">foo</option>"
"<option selected=\"selected\">bar</option>"
"<option>baz</option>")
(select-options ["foo" "bar" "baz"] '("foo" "bar"))
(str "<option selected=\"selected\">foo</option>"
"<option selected=\"selected\">bar</option>"
"<option>baz</option>")
(select-options [["Foo" 1] ["Bar" 2] ["Baz" 3]] [1 3])
(str "<option selected=\"selected\" value=\"1\">Foo</option>"
"<option value=\"2\">Bar</option>"
"<option selected=\"selected\" value=\"3\">Baz</option>")
(select-options ["foo" "bar" "baz"] #(= \b (nth % 0)))
(str "<option>foo</option>"
"<option selected=\"selected\">bar</option>"
"<option selected=\"selected\">baz</option>")))

(deftest test-drop-down
(let [options ["op1" "op2"]
Expand Down

0 comments on commit 3a46216

Please sign in to comment.