0

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

Rajkaran Mishra
  • 4,532
  • 2
  • 36
  • 61

2 Answers2

1

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| %>
Community
  • 1
  • 1
Rajkaran Mishra
  • 4,532
  • 2
  • 36
  • 61
0

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.

Wakeuphate
  • 493
  • 3
  • 13
  • ah, my apologies. Have you tried a `debugger;` statement in the change to try and manually run the `$(this).submit()` ? It may be worth doing that to see the exact issue you're having. Worth noting too that with `remote: true` off you'll trigger a page refresh. – Wakeuphate May 08 '17 at 14:18
  • Not working as in how? Is there any response from it? No errors? Nothing? Does the form ever submit? Can you see it in the console etc? – Wakeuphate May 08 '17 at 14:49
  • Found the issue it should be this not $(this) – Rajkaran Mishra May 08 '17 at 17:44