2015-09-06 97 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