3

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 %>
Community
  • 1
  • 1
Tien Yuan
  • 323
  • 1
  • 2
  • 9

2 Answers2

4

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();
  });
});
Arvoreniad
  • 510
  • 5
  • 10
1

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

Alaa Othman
  • 1,109
  • 12
  • 16