Phoenix_live_view: Programmatically submitting form results in actual form submit post request

Created on 4 Apr 2019  路  5Comments  路  Source: phoenixframework/phoenix_live_view

Actual behavior

When submitting a live view form programatically via form.submit() it triggers an actual submit post request.

<%= f = form_for @changeset, "#", [phx_submit: "save"] %>
   <%= text_input f, :name, onblur: "this.form.submit()" %>
</form>

Expected behavior

I would expect it to trigger the phx-submit event and not an actual form submit post request.

Most helpful comment

You should use form.dispatchEvent(new Event("submit", {bubbles: true}) . Thanks!

All 5 comments

Not sure if this is related, but the same thing goes for onChange, etc. of individual form elements as well..I would expect phx-change on the form to be triggered too.

I disagree with this. Current behavior conforms to the expected behavior for DOM events.

Programmatic click() or submit() do not trigger event handlers. For good reason: Often people will write a 'submit' event handler that performs some side effects and then calls submit() on the form to continue performing the basic action. If it triggered the event handler again, you'd get an infinite recursion.

What you're looking to do requires different JavaScript code:

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#Triggering_built-in_events

I am facing the same problem, the phx-submit is not being triggered but instead looks for a post request to pass the data

You should use form.dispatchEvent(new Event("submit", {bubbles: true}) . Thanks!

I just tried this on "0.13.3", "2186c55cc7c54ca45b97c6f28cfd267d1c61b5f205f3c83533704cd991bdfdec" and I'm still seeing the request. It does look like the event is also triggered, but then the page loads an error because of the missing form root.

Was this page helpful?
0 / 5 - 0 ratings