Skip to content

Instantly share code, notes, and snippets.

@simonh1000
Created August 16, 2016 07:08
Show Gist options
  • Save simonh1000/07dbfae7ad5a25f5d108ea59e9ee9a29 to your computer and use it in GitHub Desktop.
Save simonh1000/07dbfae7ad5a25f5d108ea59e9ee9a29 to your computer and use it in GitHub Desktop.
module Test exposing (..)
import Html exposing (..)
import Html.App as App
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import List exposing (map)
import Json.Decode as Json
type alias Model =
Maybe String
init = Nothing
type Msg
= Switch String
update (Switch s) model =
Debug.log"" <| Just s
view model =
let
kvs =
[ ("1", "One")
, ("2", "Two")
]
makeOpts lst selectedKey =
lst
|> map (\(k, v) ->
option
[ value k
, selected <| k == selectedKey
] [ text v ])
in
select
[ onInput Switch ] <|
case model of
Just s ->
makeOpts kvs s
Nothing ->
makeOpts
(("0", "Zero") :: kvs)
"0"
main = App.beginnerProgram
{ model = init
, view = view
, update = update
}
onChange : (String -> a) -> Attribute a
onChange messageCreator =
on "change" (Json.map messageCreator targetValue)
@pdamoc
Copy link

pdamoc commented Aug 16, 2016

Using Html.Keyed solves this:

module Test exposing (..)

import Html exposing (..)
import Html.App as App
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import List exposing (map)
import Json.Decode as Json
import Html.Keyed


type alias Model =
    Maybe String


init =
    Nothing


type Msg
    = Switch String


update (Switch s) model =
    Debug.log "" <| Just s


keyedSelect =
    Html.Keyed.node "select"


view model =
    let
        kvs =
            [ ( "1", "One" )
            , ( "2", "Two" )
            , ( "3", "Three" )
            ]

        makeOpts lst selectedKey =
            lst
                |> map
                    (\( k, v ) ->
                        ( k
                        , option
                            [ value k
                            , selected <| k == selectedKey
                            ]
                            [ text v ]
                        )
                    )
    in
        keyedSelect [ onInput Switch ]
            (case model of
                Just s ->
                    makeOpts kvs s

                Nothing ->
                    makeOpts (( "0", "Zero" ) :: kvs)
                        "0"
            )


main =
    App.beginnerProgram
        { model = init
        , view = view
        , update = update
        }


onChange : (String -> a) -> Attribute a
onChange messageCreator =
    on "change" (Json.map messageCreator targetValue)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment