From 3a46216346df2fc136b27f8f0d8f04deb6656009 Mon Sep 17 00:00:00 2001 From: Xuan Wu Date: Sun, 4 Feb 2024 14:36:58 -0800 Subject: [PATCH] Allow multiple selected options in select elements 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. --- src/hiccup/form.clj | 10 ++++++++-- test/hiccup/form_test.clj | 20 +++++++++++++++++--- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/src/hiccup/form.clj b/src/hiccup/form.clj index 7c60fae..c072252 100644 --- a/src/hiccup/form.clj +++ b/src/hiccup/form.clj @@ -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)) @@ -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 `