Search code examples
elmelm-ui

How Do I make an Elm-UI element respond to pressing "Enter"


I need to make my app send a message when Enter is pressed. I have an element like:

Input.text [] { onChange = UpdateText, text = model.text, placeholder=Nothing }

How can I make it submit when enter is pressed?

Note: Q/A copied from the Elm-Slack for findability.


Solution

  • This is mentioned in the Elm-UI docs .

    Basically, you define a function that sends a msg when the Enter Key is pressed and embed that into your view function:

    onEnter : msg -> Element.Attribute msg
    onEnter msg =
        Element.htmlAttribute
            (Html.Events.on "keyup"
                (Decode.field "key" Decode.string
                    |> Decode.andThen
                        (\key ->
                            if key == "Enter" then
                                Decode.succeed msg
    
                            else
                                Decode.fail "Not the enter key"
                        )
                )
            )
    

    Then embed it into the attributes of an element in your view:

    Input.text
        [ onEnter EnterWasPressed ]
        { onChange = UpdateText
        , text = model.text
        , placeholder = Nothing
        }
    

    Ellie Link (From docs): https://ellie-app.com/5X6jBKtxzdpa1