Link

Submit a Form Programmatically

by @julianrubisch julianrubisch

<div controller="remote-form">
  <%= form_with(model: @article, html: { data: { action: "ajax:success->remote-form#onPostSuccess" } }) do |f| %>
    <%= select_tag "author", options_from_collection_for_select(@people, "id", "name"),
                   data: { action: "change->remote-form#update" } %>
  <% end %>
</div>

Won’t Work

import { Controller } from "stimulus";

export default class extends Controller {
  onPostSuccess(event) {
    console.log("success!");
  }

  update() {
    this.element.submit();
  }
}

Works

import Rails from "@rails/ujs";
import { Controller } from "stimulus";

export default class extends Controller {
  onPostSuccess(event) {
    console.log("success!");
  }

  update() {
    Rails.fire(this.element, 'submit');
  }
}

Explanation

Rails-ujs intercepts form submit events that have a data-remote="true" attribute on the form element, but in the case of the HTMLFormElement.submit() method called, no event is even fired.

Reference