1

Let's say I have a select element to choose a person, and I want to have a certain person, say with id = 3, to be initially selected. How do I pass this id down into my options, and then set the selected attribute to True in that options?

Some sample code:

personSelect : List Person -> String -> Html Msg
personSelect : personList selectedId =
    div []
        [ select [] (List.map personOption personList) ]


personOption : Person -> Html Msg
personOption : person = 
    option [ value (toString person.id) ] [ text person.name ]

Specifically, how do I get "selectedId" passed to "personOption"? Can I even do this using List.map?

Thanks very much!

Gabe
  • 1,166
  • 1
  • 12
  • 15

1 Answers1

7

Provide selectedId as an argument to personOption and exploit that you can partially apply functions in Elm. That is, when you give a function some but not all of the arguments that it needs, you get back a function waiting for the remaining arguments.

First, add selectedId to personOptions and render the option as selected if it matches.

personOption : String -> Person -> Html Msg
personOption selectedId person = 
  option 
    [ selected (selectedId == person.id)
    , value (toString person.id)
    ]
    [ text person.name ]

Then partially apply personOption by giving it its first argument before passing it on to map:

personSelect : List Person -> String -> Html Msg
personSelect personList selectedId =
  div []
    [ select [] 
        (List.map (personOption selectedId) personList) 
        -- personOption selectedId : String -> Html Msg
     ]
Søren Debois
  • 5,598
  • 26
  • 48