如何在Elm中获取多选的选项?

时间:2016-10-14 13:03:46

标签: elm

我见过what is required for a getting the selected index of a single select,但我有兴趣从多选中获取所有选定的选项。我无法弄清楚如何做到这一点。

我尝试了以下但我怀疑Json解码器失败了。我不是百分之百确定,因为解码发生在虚拟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))

我可以在不使用端口的情况下执行此操作吗?

1 个答案:

答案 0 :(得分:2)

解码器失败,因为event.target.selectedOptions不是a 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