Skip to content

Instantly share code, notes, and snippets.

@grassdog
Last active October 14, 2016 02:11
Show Gist options
  • Save grassdog/82bdb72a1b536331c0ba25138b2f3b5f to your computer and use it in GitHub Desktop.
Save grassdog/82bdb72a1b536331c0ba25138b2f3b5f to your computer and use it in GitHub Desktop.
An attempt to extract the selected values of a multi select in Elm
module Main exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.App as Html
import Html.Events exposing (onInput, on, targetValue)
import Json.Decode as Json
import String exposing (join)
main : Program Flags
main =
Html.programWithFlags { init = init, update = update, subscriptions = subscriptions, view = view }
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- INIT
type alias Flags =
{}
initialModel : Flags -> Model
initialModel flags =
{ selectedSingleInt = []
, selectedMultipleInts = []
}
init : Flags -> ( Model, Cmd msg )
init flags =
( initialModel flags, Cmd.none )
-- MODEL
type alias Model =
{ selectedMultipleInts : List Int
, selectedSingleInt : List Int
}
-- UPDATE
type Msg
= NoOp
| SetSingleInt Int
| SetMultipleInts (List Int)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
NoOp ->
( model, Cmd.none )
SetSingleInt newAccount ->
( { model | selectedSingleInt = [ newAccount ] }, Cmd.none )
SetMultipleInts newCategories ->
( { model | selectedMultipleInts = newCategories }, Cmd.none )
-- VIEW
view : Model -> Html Msg
view model =
div []
[ select (onSelect SetMultipleInts) (List.map myOption [1..4])
, div []
[ span [] [ text "Multiple " ]
, span [] [ text <| String.join ", " <| List.map toString model.selectedMultipleInts ]
]
, select (onSingleSelect SetSingleInt) (List.map myOption [1..4])
, div []
[ span [] [ text "Single " ]
, span [] [ text <| String.join ", " <| List.map toString model.selectedSingleInt ]
]
]
myOption : Int -> Html Msg
myOption id =
option [ value (toString id) ] [ text <| "Option " ++ (toString id) ]
-- Single select
-- ** This one works fine and returns the correct index --
targetSelectedIndex : Json.Decoder Int
targetSelectedIndex =
Json.at [ "target", "selectedIndex" ] Json.int
onSingleSelect : (Int -> msg) -> List (Html.Attribute msg)
onSingleSelect msg =
[ on "change" (Json.map msg targetSelectedIndex) ]
-- Multi-select
-- ** This doesn't seem to work :( --
targetSelectedOptions : Json.Decoder (List Int)
targetSelectedOptions =
Json.at [ "target", "selectedOptions" ] (Json.list (Json.at [ "value" ] Json.int))
onSelect : (List Int -> msg) -> List (Html.Attribute msg)
onSelect msg =
[ on "change" (Json.map msg targetSelectedOptions), multiple True ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment