Event listener other than onChange on a text input of elm-ui?

Learning elm-ui I found the Element.Input.text can only use onChange event listener. This event fires on every keystrokes. That is actually the onkeydown on a raw input element. But I want the real onChange ie., fires only when I lost the focus or hit an enter key. How to do that with the Element.Input.text of elm-ui ?

I got a hint from stackoverflow which suggests to use htmlAttribute to add an keyup listener.

But using Element.htmlAttribute looks awkward. Not only it need a lot more code, you need also define a do-nothing Message tag for the original onChange of the Element.Input.text as it’s mandatory.

Is there a better way?

Just found there is a feature-suggestion closely related to my problem. Looks like using htmlAttribute + Html.Events is the only way to go for now.

Yeah, I seem to end up defining this just about every app, with and without elm-ui

onChange : (String -> msg) -> Attribute msg
onChange tagger =
  targetValue Json.Decode.string tagger
    |> Html.Events.on "change"
    |> htmlAttribute

targetValue : Json.Decode.Decoder a -> (a -> msg) -> Json.Decode.Decoder msg
targetValue decoder tagger =
  Json.Decode.map tagger
    (Json.Decode.at ["target", "value" ] decoder)
1 Like

I’m curious, what are your use cases for the "change" event?

Simple and good question! I just realized that the builtin oninput support of elm-ui is actually indeed more useful than onchange. A day ago I’m a bit annoyed and wondering why they don’t give onchange a direct support. Now I understand this is based on the nature of elm app. They’re trying help us to capture as much state-changes as possible(which is good). This give us fine-grained control over the ui and ease the data exchange with the backend. Please point out if my understanding is wrong(I’m learning)

In traditional html/css UI development, we care about onchange much more than oninput, because most of time that’s the point we get into act. Things are changed in elm and I’ll (happily) roll with it.

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.