LoginSignup
0
2

More than 1 year has passed since last update.

form_withを使ったRails.fireの使い方

Last updated at Posted at 2022-01-22

form_withを使ったRails.fireの使い方

JS側からsubmitを行う方法として、Rails.fireを使う方法があります。
Rails.fireを使うとajax通信が可能になります。
form_withの中で、local: falseを指定することによって、html.erbがコンパイルされた結果のhtmlに「data-remote="true"」が記述される様になり、ajax通信が可能になります。

  • html.erb側
<%= form_with(model: @hoge, url: '', id: 'hoge_form', local: false) do |f| %>
  <%= f.text_field :name, placeholder: 'test' %>
  <%= f.button id: 'hoge_submit' ,type:'button' %>
<% end %>
  • js側
import Rails from "@rails/ujs";

$(document).on ('turbolinks:load', function(){
  $('#hoge_submit').on('click',function(e) {

    Rails.fire($("#hoge_form")[0],'submit');
  }
});
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2