Reason for the "Elm way" of retrieving HTML input values?

New to Elm, sorry if this has been covered, but haven’t found much discussion.

tl;dr: What’s the design rationale (or technical reason) for not being able to directly retrieve the value attribute of an HTML input, e.g. through some kind of getter function working on an Html instance?

Say my view has something like:

input [] [],
button [] [text "Submit"]

When I click the button, I’d like to do something with the input value. I assumed at first it’d work something like:

let
  myInput = input [] []
in
button [onClick (DoStuffWith (getValue myInput))] [text "Submit"]

I’m aware from a couple StackOverflow questions that stashing input values in the model is “the Elm way”, but curious to know why. Is it a limitation of the HTML library, or of the language itself that I haven’t grasped yet, or a more intentional design decision?

What do you want to do with the input value? Elm has a specific way of handling use interaction (and all other interactions to), see https://guide.elm-lang.org/architecture/

It is more of an intentional decision and it is related to how Elm views state.

The Html functions are conceptually pure. Of course, the actual nodes that they produce are still stateful due to the underlying implementation but as far as Elm is concerned, they are considered stateless.

So, input [] [], from Elm’s perspective, is an empty input field that is always empty.

getValue myInput makes not sense (conceptually) in Elm since you give myInput the value that it holds (conceptually).

Note that for :

input [] [],
button [] [text "Submit"]

you can still extract the value of the input using decoders and the fact that it is the previousSibling of the button BUT that is not advisable. It would be the equivalent of breaking encapsulation and relying on some internal representation that might change.

6 Likes

It’s also worth noting that all values in Elm are immutable. myInput is not a reference to a value that can change over time. This means that even if you had a function getValue : Html a -> String, calling getValue myInput would always give you an empty string, no matter what the user typed into the input.

More conceptually, Elm view functions don’t have references to the actual DOM. Instead, they construct new (virtual) nodes based on the arguments you give the function. This means the only source of information for a view function are its arguments. It cannot query the DOM.

4 Likes

And this is of course true for all functions in Elm - only source of information for any function are its arguments.

1 Like

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