Search code examples
jqueryruby-on-railsruby-on-rails-5ujs

Rails 5: Submit form with jQuery


I am trying to submit a form with jQuery if any of the element changes. For now I am not using remote: true.

Here is the code that renders the partial:

views/assets/index.html.erb
<%= render @assets %>

Code for partial:

views/assets/_asset.html.erb
<%= form_for [asset.project, asset] do |f| %>
  ...
<% end %>

Following is the javascript code for form submit:

$(document).on('turbolinks:load', function() {
  if (!($(".assets.index").length > 0)) return;

  $('.edit_asset').change(function() {
    alert("submitting..");
    $(this).submit();
  });
});

It's doing the alert but form is not getting submitted, please suggest..

enter image description here


Solution

  • Actually the issue was $(this) vs this. So it should be

    this.submit(); # or
    $(this)[0].submit();
    

    But client side validations on form elements like required: true won't work as it's bound to the submit button of the form. So we have to trigger that event, here is how I am doing it:

    views/assets/_asset.html.erb
    <%= form_for [asset.project, asset] do |f| %>
      ...
      <%= f.submit "Update", style: "display: none;" %>
      ...
    <% end %>
    

    Javascript code will be:

    $(document).on('turbolinks:load', function() {
      if (!($(".assets.index").length > 0)) return;
    
      jQuery.fn.submitOnChange = function() {
        $(this).change(function() {
          $(this).find("input[type=submit]").click();
        })
        return this;
      }
      $('.edit_asset').submitOnChange();
    });
    

    If we want to do this remotely, we have to add remote: true & authenticity_token: true to the form_for, so it will be:

    <%= form_for([asset.project, asset], authenticity_token: true, remote: true) do |f| %>