user6655060
user6655060

Reputation:

Elm beginner's question: Html input seems to be preventing model property update

I have created a simple Elm program that takes in an input via an Html input and, when a submit button is clicked, updates an Html text with a based on the input value.

In addition there is a reset button which resets the model to its initial value.

What I am finding is that, when reset is clicked, the Html text is reset to its initial value however the Html input is not.

What am I missing here?

module Main exposing (main)

import Browser
import Html exposing (Html, button, div, text, input)
import Html.Events exposing (onClick, onInput)

type alias Model =
    { name : String,
      message : String
    }

initialModel : Model
    initialModel =
    { name = "",
      message = "" }

type Msg
    = SubmitName
    | ResetName
    | UpdateName String

update : Msg -> Model -> Model
update msg model =
    case msg of
        UpdateName text -> 
            { model | name = text }

        SubmitName ->
            { model | 
            message = 
               if model.name =="Dugald McDougall" then 
                   "What a great name!"
               else 
                   "Meh..."
            }

       ResetName ->
           initialModel

view : Model -> Html Msg
view model =
    div []
        [ input [ onInput UpdateName ] []
        , div [] [ button [ onClick SubmitName ] [ text "Submit" ]
        , button [ onClick ResetName ] [ text "Reset" ] 
        , div[] [ text <| model.message ] ]
        ]

main : Program () Model Msg
main =
    Browser.sandbox
        { init = initialModel
         , view = view
         , update = update
        }

Upvotes: 1

Views: 633

Answers (1)

Sidney
Sidney

Reputation: 4775

The problem is that the input keeps track of its own value in the DOM, and it does not know about the current value in the model. You need to use a "controlled" input where the value is forced to stay in sync with the model.

import Html.Attributes exposing (value)

...

input [ onInput UpdateName, value model.name ] []

Whenever the model changes, the Elm virtual DOM updates the input in the real DOM so that it has the new value.

Upvotes: 3

Related Questions