I have a <select>
HTML element with 3 options and a <p>
element. In the <p>
element I want to print index of the currently selected item in <select>
. E.g. if I select the first option, it should print 0, if I select the second option, it should print 1, and so on. How do I proceed from the minimal code, which is given below?
import Html as H exposing (Html)
import Maybe
import Signal as S exposing (Address, (<~))
type alias Model = { selected : Maybe Int }
model = { selected = Nothing }
type Action = NoOp | Select Int
update action model =
case action of
NoOp -> model
Select n -> { model | selected <- Just n }
view address model =
H.div []
[ H.select [] [ H.option [] [ H.text "0" ]
, H.option [] [ H.text "1" ]
, H.option [] [ H.text "2" ]
]
, H.p [] [ H.text <| Maybe.withDefault ""
<| Maybe.map toString model.selected ]
]
actions = Signal.mailbox NoOp
main = view actions.address <~ S.foldp update model actions.signal
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 usingon
. It has a type: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 aselectedIndex
property.The final code would look like this:
Updated to Elm-0.18
You can run it in browser here https://runelm.io/c/xum