5

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.

Ben
  • 5,952
  • 4
  • 33
  • 44

1 Answers1

12

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

Ben
  • 5,952
  • 4
  • 33
  • 44
  • 3
    This seems like a strange thing to leave out. I wonder why. – ijt Oct 02 '20 at 22:19
  • What if I don't want the onChange being triggered? Since the onChange is mandatory in elm-ui, I still need a Message tag which do nothing in the `update` function? weird. – John Wang Mar 04 '21 at 07:39