2015-09-06 95 views
11

我有一个<select> HTML元素有3个选项和一个<p>元素。在<p>元素中,我想在<select>中打印当前选定项目的索引。例如。如果我选择第一个选项,则应打印0,如果选择第二个选项,则应打印1,依此类推。我如何从最小代码开始,如下所示?如何在Elm中打印所选选项的索引?

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 

回答

18

有一个在elm-html 2.0.0很多different events,但没有相关的<select> HTML元素。所以你绝对需要一个自定义的事件处理程序,你可以使用on创建。它有一个类型:

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

被触发每次选择<select>内的选项被称为“change”时间的事件。你需要的是targetSelectedIndexelm-community/html-extra它使用selectedIndex属性。

最后的代码应该是这样的:

更新榆树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 } 

你可以在浏览器中在这里没有运行https://runelm.io/c/xum

+0

,你可以没有削减? :) –

+0

软件包的缩写名称。这个例子对我有很大的帮助,但是我不得不在文本编辑器中复制粘贴它,并在我能够理解之前将JD更改为Json.Decode等。 –

+0

如果你有时间的话,看到elm-0.17更新会很高兴。如果我觉得我对选择选项的理解足够好,我会尽力去做。 – MichaelJones