Refactoring Evan's viewInput function in elm-todomvc

dwayne profile image Dwayne Crooks ・1 min read

I don't like that we have to write our own onEnter function to make viewInput work.

By wrapping the input element in a form element we can achieve the same goal, write simpler code and keep the HTML semantic.

viewInput : String -> Html Msg
viewInput task =
    [ class "header" ]
    [ h1 [] [ text "todos" ]
    , form
        [ onSubmit Add ]
        [ input
            [ class "new-todo"
            , placeholder "What needs to be done?"
            , autofocus True
            , value task
            , name "newTodo"
            , onInput UpdateField

Now when you type a description and press ENTER a submit event is fired on the form. The onSubmit event handler detects the submit event with preventDefault and propagates the Add message to the update function.

What do you think? Is this version any better?

Posted on Aug 7 '19 by:

dwayne profile

Dwayne Crooks


A full stack web developer who has an interest in programming language theory, interpreters, compilers and type theory. I enjoy programming with Elm and Haskell in my free time.


markdown guide

This version is the standard way of programmatically doing HTML forms. This is the way to benefit of all the features that the browser can provide to help the user. You use the onEnter or other hacks when you need nonstandard functionality.