morinap
Triggering LiveView Form Change Event from Javascript
I am using LiveView to render a form and a phx_change event to send updates back to the controller. I’m also using an extra library (Select2: https://select2.org/) as a more robust select field control for a select input on the form. I have a JavaScript event listener tied to the Select2’s change event so that I can perform certain actions, and I’d like in my event listener to then be able to push the phx_change event back to the LiveView.
I’ve inspected the change event payload and noted it’s like any other event and just contains an encoded chunk of the full form data, so I can replicate that behavior in my own code if need be, but ideally I’d like a LiveView JS-interop way to do this programmatically. Something either like this.pushFormChange() or finding the form instance and making a trigger call on the event that the JS interop has bound to, but so far I’ve been unable to find anything either in the documentation, in the source code, or in some trial-and-error that works the way I want.
Is this something that’s possible or that anybody has done? Alternatively, is my approach simply wrong here?
Marked As Solved
chrismccord
via a hook on the input tag:
To trigger a phx-change:
this.el.dispatchEvent(new Event("input", {bubbles: true}))
To trigger a phx-submit:
this.el.dispatchEvent(new Event("submit", {bubbles: true}))
Also Liked
BartOtten
@chrismccord Have been searching for this answer for some time too. Seeing the answer got 12 likes, I suppose I was not the only one. Maybe it’s a good idea to add it to the JavaScript interoperability — Phoenix LiveView v1.2.5? That is were I tried to find the answer.
mhmtarif
soup
You might need to post some code. Are you sure the element exists or the ID is correct? Cannot read property 'querySelectorAll' of null implies something is trying to call element_but_its_null.querySelectorAll.
Last Post!
mphuie
How would I trigger a form phx_submit from a global hotkey?
IE ctrl + s anywhere on the page would trigger it via window.onkeydown.
Also reading the javascript interop docs, it looks like you add client side JS in app.js, which is loaded for every page? Why can’t you inline the JS into your specific view?
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security









