How to print index of selected option in Elm?

泪湿孤枕 提交于 2019-12-03 11:29:52
Mirzhan Irkegulov

There's a lot of different events in elm-html 2.0.0, but nothing relevant to the <select> HTML element. So you definitely need a custom event handler, which you can create using on. It has a type:

on : String -> Decoder a -> (a -> Message a) -> Attribute

The event that is triggered every time you select an option inside the <select> is called “change”. What you need is targetSelectedIndex from elm-community/html-extra which ustilizes a selectedIndex property.

The final code would look like this:

Updated to Elm-0.18

import Html exposing (..)
import Html.Events exposing (on, onClick)
import Html.Attributes exposing (..)
import Json.Decode as Json
import Html.Events.Extra exposing (targetSelectedIndex)


type alias Model =
    { selected : Maybe Int }


model : Model
model =
    { selected = Nothing }


type Msg
    = NoOp
    | Select (Maybe Int)


update : Msg -> Model -> Model
update msg model =
    case msg of
        NoOp ->
            model

        Select s ->
            { model | selected = s }


view : Model -> Html Msg
view model =
    let
        selectEvent =
            on "change"
                (Json.map Select targetSelectedIndex)
    in
        div []
            [ select [ size 3, selectEvent ]
                [ option [] [ text "1" ]
                , option [] [ text "2" ]
                , option [] [ text "3" ]
                ]
        , p []
            [ text <|
                Maybe.withDefault "" <|
                    Maybe.map toString model.selected
            ]
        ]


main : Program Never Model Msg
main =
    beginnerProgram { model = model, view = view, update = update }

You can run it in browser here https://runelm.io/c/xum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!