I started using Elm relatively recently, only for a few weeks now, and it’s my first foray into functional programming. As I was working on a small feature to learn the language, I came across a situation where I wanted to simultaneously grab multiple values from a field. Well
Html.Events.onSubmit wasn’t cutting it so I ended up creating my own event listener to do what I wanted.
I’m sharing this example here in case it is useful to anyone else, but also for feedback. It seems to work well but perhaps there are some pitfalls or gotchas with this approach that I’m not aware, as opposed to what I’ve seen before with updating the model using
onInput with every keypress for each each field.
This approach seemed better for my case where I really don’t care what’s in the field until the user chooses to submit it.
Here’s the full example: https://ellie-app.com/7V9DpNRWffTa1
Here’s my event listener:
onFormSubmit : (FormData -> msg) -> Html.Attribute msg onFormSubmit tagger = preventDefaultOn "submit" (D.map alwaysPreventDefault (D.map tagger formValues)) alwaysPreventDefault : msg -> ( msg, Bool ) alwaysPreventDefault msg = ( msg, True ) formValues : D.Decoder FormData formValues = D.map2 FormData (D.at ["target", "elements", "0", "value"] D.string) (D.at ["target", "elements", "1", "value"] D.string)
Hopefully this helps someone and thank you in advance for any feedback, I’m becoming well aware of what I don’t yet know.
I copied some bits from the
Html.Events implementation of different core events, so I’m still wrapping my head around exactly how that works.