我已经了解了获取单个选择的选定索引所需的内容,但我有兴趣从多选中获取所有选定的选项。我一直无法弄清楚如何做到这一点。
我尝试了以下操作,但我怀疑 Json 解码器失败。但我不能 100% 确定这一点,因为解码发生在虚拟 dom 代码中,并且那里的任何错误都会被丢弃。
type Msg
= SetMultipleInts (List Int)
-- I'm not seeing the SetMultipleInts message when I click on the multiselect
view model =
div []
[ select (onSelect SetMultipleInts) (List.map myOption [1..4]) ]
myOption : Int -> Html Msg
myOption id =
option [ value (toString id) ] [ text <| "Option " ++ (toString id) ]
-- I'm not seeing anything happen in the onchange
onMultiSelect : (List Int -> msg) -> List (Html.Attribute msg)
onMultiSelect msg =
[ on "change" (Json.map msg targetSelectedOptions), multiple True ]
targetSelectedOptions : Json.Decoder (List Int)
targetSelectedOptions =
Json.at [ "target", "selectedOptions" ] (Json.list (Json.at [ "value" ] Json.int))
Run Code Online (Sandbox Code Playgroud)
我可以在不使用端口的情况下执行此操作吗?
解码器失败,因为event.target.selectedOptions不是 JavaScript 数组。当你不能使用时Json.Decode.list,你可以使用Json.Decode.keyValuePairs。
以下是如何使用它的示例。您可能需要extractValues根据您对空选择等的反应方式进行以下更改。
targetSelectedOptions : Json.Decoder (List String)
targetSelectedOptions =
let
maybeValues =
Json.at [ "target", "selectedOptions" ]
<| Json.keyValuePairs
<| Json.maybe ("value" := Json.string)
extractValues mv =
Ok (List.filterMap snd mv)
in Json.customDecoder maybeValues extractValues
Run Code Online (Sandbox Code Playgroud)