Search code examples
elm

Having radio buttons reflect the model


In this example, the initial fontSize is Medium. This is reflected in the size of the font, but the medium radio button is not selected. Is there a way to make the radio button always reflect the current fontSize?


Solution

  • Is this what you were looking for?

    view : Model -> Html Msg
    view model =
      div []
        [ fieldset []
            [ radio "Small" (model.fontSize == Small) (SwitchTo Small)
            , radio "Medium"(model.fontSize == Medium)  (SwitchTo Medium)
            , radio "Large" (model.fontSize == Large) (SwitchTo Large)
            ]
        , Markdown.toHtml [ sizeToStyle model.fontSize ] model.content
        ]
    
    
    radio : String -> Bool > msg -> Html msg
    radio value isChecked msg =
      label
        [ style [("padding", "20px")]
        ]
        [ input [ type_ "radio", name "font-size", onInput msg, checked isChecked ] []
        , text value
        ]
    

    Note that I changed onClick to onInput, which I think is better practise for form selections.

    As an aside, I tend to put the msg parameter at the beginning of the type signature as that's the least likely to be part of a pipeline of functions:

    radio : msg -> Bool -> String -> Html msg