How do you add an onchange event handler in Elm?

Viewed 87

I need to add an onchange event handler in an input element in my Elm project but it does not seem to be available. For example, if I want to add and onclick event handler, I can use the below code:

input [ onClick   { desc = "ClickFunction", info = model.name } ] []

But when I try to do the below for onchange, it does not work:

input [ onChange   { desc = "ChangeFunction", info = model.name } ] []

This is the error message I get:

NAMING ERROR - I cannot find a `onChange` variable:
These names seem close though:
31|                     [ onChange   { desc = "ChangeFunction", info = model.name ] []
                                                                                                    #^^^^^^^^#
    #onCheck#
    #srclang#
    #enctype#
    #lang#

So how do I implement the onchange event handler?

1 Answers

Typically the input event is a better choice than the change event, which is why it isn't included in the default set of event handlers. However, if you have a case where you don't want a message in Elm until the change is committed, you have a couple of options.

You maybe want to use Html.Events.Extra.onChange from the elm-community/html-extra package.

You can also use Html.Events.on to create a custom handler. For example,

onChange : (String -> msg) -> Attribute msg
onChange tagger =
    on "change" (targetValue |> Json.Decode.map tagger)

See an Ellie app that demonstrates this example. Note that you can change onChange to onInput in this example and it works just the same.

Related