Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

elm

elm-ui

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.

like image 724
Ben Avatar asked Dec 18 '22 16:12

Ben


1 Answers

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

like image 108
Ben Avatar answered Mar 04 '23 07:03

Ben