I’m very much an elm beginner and have come across this problem of trying to change the state of an HTML radio button when the model changes.
I include a stripped down copy of the code which illustrates the problem I’m having.
The page displays a list of indexes, each index in the list has a radio button. The ‘+’ button adds a new index to the list.
-
A Initial state, a single, unselected radio box.
-
B Select the radio box next to ‘0’
-
C Click the ‘+’ button to add a new , index ‘1’
The previous index ‘0’ remains selected. I’d like to change this behaviour so that the most recently created index, in this case 1’, becomes selected.
module Main exposing (main)
import Browser
import Html exposing (..)
import Html.Attributes exposing (name, style, type_, value)
import Html.Events exposing (onClick, onInput)
type Msg
= EntryAdded
| EntrySelected String
type alias Entry =
{ index : Int }
type alias Model =
{ selected : Maybe Int
, entries : List Entry
}
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = \_ -> Sub.none
}
init : () -> ( Model, Cmd Msg )
init _ =
( Model Nothing [ Entry 0 ]
, Cmd.none
)
view : Model -> Html Msg
view model =
div []
[ ul [ style "list-style-type" "none" ]
(List.map
(\entry ->
div
[]
[ li []
[ text (String.fromInt entry.index)
, input
[ type_ "radio"
, name "entrySelector"
, value <| String.fromInt entry.index
, onInput EntrySelected
]
[]
]
]
)
model.entries
)
, button [ onClick EntryAdded ] [ text "+" ]
]
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
EntryAdded ->
let
last_item =
List.length model.entries
in
( { model
| entries = List.append model.entries [ Entry last_item ]
, selected = Just last_item
}
, Cmd.none
)
EntrySelected index ->
( { model | selected = String.toInt index }
, Cmd.none
)