简体   繁体   中英

Rails form not submitting on change with ajax

I'm working on a little todo list app with ruby on rails and I'd like to submit a form via ajax when a checkbox is selected. I've been following this guide to try and do this.

Changing the checkbox didn't submit the form though, so I searched on SO for similar questions and made some updates to my code.

  1. Using on() instead of live()
  2. Submitting the closest form instead of form.first since I have a list of these forms on the same page

It still won't submit though. I have a feeling it's not watching '.submittable' correctly because I can't even get an alert to flash when a checkbox is clicked.

Any pointers? Have I forgotten something? Thanks.

index.html.erb

<table class="table table-striped">
  <tr>
    <th>Task Description</th>
    <th width="15%">Days Left</th>
    <th width="15%">Completed?</th>
  </tr>
  <% @tasks.each do |task| %>
  <tr>
    <td><%= task.description %></td>
    <td><%= task.days_remaining %> days left</td>
    <td><%= form_for task, remote: true  do |f| %>
        <%= f.check_box 'completed', id: "task-#{task.id}", class: 'submittable' %>
    <% end %>
        </td>
  </tr>
  <% end %>
</table>

application.js

$('.submittable').on('change', function() {
  $(this).closest('form').submit();
});

update.js.erb

<% if @task.updated? %>
   $('#task-' +<%= @task.id %>).prepend("Yes");
<% else %>
   $('#task-' +<%= @task.id %>).prepend("<div class='alert alert-error'><%= flash[:error] %></div>");
<% end %>

Your code doesn't seem to be wrapped in a call to $(document).ready() , so jQuery is probably trying to bind the event before your checkbox loads. Try this instead:

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

You have to wait until the dom is loads

$(function(){
 $('.submittable').on('change', function() {
   $(this).closest('form').submit();
 });
});

then make sure in your controller update action

respond_to do |format|
  if @object.update(object_params)
    .
    .
    format.js
  else
   .
   .
  end
end

see this episode of railscasts he is explaining what you want to do

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM