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.
- Using on() instead of live()
- 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 %>