0

I have a Rails app with Datatables. I am trying to add a select to each row that completes a simple JS call to update the record. I started with adding:

onchange: "this.form.submit();"

to my selects. This works EXCEPT the form does not respect the remote: true option for the form:

<form class="edit_flag" id="edit_flag_52" action="/myurl/path/id" accept-charset="UTF-8" data-remote="true" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="_method" value="patch">
<select name="name" id="id_1" onchange: "this.form.submit();`" class: "myclass"><option value="">n/a</option>
<option value="10">Steve</option>
<option value="4">Joe</option>
<option value="9">Frank</option>
<option selected="selected" value="55">Dan</option></select>
</form>

The '/myurl/path/id.js' loads in the browser vs remote. After some searching is seems that because the forms are loaded via AJAX that causes this issue. I have read about binding the events etc. - JS is not my strong skill so looking for some pointers here. Here are the links I have found:

The main issue I have is that my view has multiple forms on the same page.

I tried this:

$(document).on('change', '.myclass', function() {
  this.form.submit();
});

This still has the same problem where the form does not submit remote.

UPDATE

Perhaps I am missing something here - I added a plain old submit button. This method works as expected. The form submits in the background. I even added a call in my update.js.erb file that reloads the datatable (which was my plan once I got the select working).

Dan Tappin
  • 2,692
  • 3
  • 37
  • 77

1 Answers1

0

Ended up stumbling across this:

$(document).ready(function() {
  $('body').on('change', '.myclass', function() {
    $(this).closest("form").submit();
  });
});

It works - not sure why. Hope this helps someone else. Would accept another answer that explains why this works vs. what I had before.

Dan Tappin
  • 2,692
  • 3
  • 37
  • 77