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.
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.