drop down menu - How to use select (dropdown) tag in Elm lang -


i want render simple dropdown within elm app following code it's not working expected. want keep union type role in place , avoid using strings if it's possible.

what's best way work dropdown in elm? didn't find example yet.

import html exposing (..) import html.app exposing (beginnerprogram) import html.events exposing (..) import html.attributes exposing (..) import json.decode  main =   beginnerprogram     { model = initialmodel     , view = view     , update = update     }  initialmodel =   { role = none   }  type role   = none   | admin   | user  type alias model =    { role: role   }  type msg   = selectrole role   update msg model =   case msg of     selectrole role ->       { model | role = role }   view : model -> html msg view model =   div     []     [ select         [ ]         [ viewoption none         , viewoption admin         , viewoption user         ]     , pre [] [ text <| tostring model ]     ]    viewoption : role -> html msg viewoption role =   option     [ onclick (selectrole role) ]     [ text <| tostring role ] 

the onclick handler doesn't work option elements. you'll instead want capture change event , @ json targetvalue see selected.

i first remove onclick handler , instead set option tag's value attribute:

viewoption : role -> html msg viewoption role =   option     [ value <| tostring role ]     [ text <| tostring role ] 

now you'll need json decoder can take event's targetvalue string , convert role:

targetvalueroledecoder : json.decode.decoder role targetvalueroledecoder =   targetvalue `json.decode.andthen` \val ->     case val of       "admin" -> json.decode.succeed admin       "user" -> json.decode.succeed user       "none" -> json.decode.succeed none       _ -> json.decode.fail ("invalid role: " ++ val) 

now need add select change event handler:

    [ select         [ on "change" (json.decode.map selectrole targetvalueroledecoder)         ]         [ viewoption none         , viewoption admin         , viewoption user         ] 

the fact have resort strings merely artifact of having translate values dom events valid union types. you'll still want keep role union type; have create json decoders targeting each union type now, since elm not (yet) support kind of automatic string union type function.


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -