Rajkaran Mishra
Rajkaran Mishra

Reputation: 4952

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

Upvotes: 0

Views: 5663

Answers (2)

Rajkaran Mishra
Rajkaran Mishra

Reputation: 4952

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| %>

Upvotes: 1

Wakeuphate
Wakeuphate

Reputation: 503

Your issue is that $(this) in the .change for .edit_asset is targeting that element and trying to submit it. You need to find the form object and submit that instead:

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

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

This could also be a bit stressful on your install, I'd recommend having a bit of a timeout after the changes and then submitting rather than constantly hammering your rails install with submit requests.

Upvotes: 0

Related Questions