我正在使用 ruby on rails 开发一个待办事项列表小应用程序,我想在选中复选框时通过 ajax 提交表单。我一直在关注this guide尝试并做到这一点。
更改复选框并没有提交表单,所以我在 SO 上搜索了类似的问题并对我的代码进行了一些更新。
- 使用on() instead of live()
- 提交 closest form instead of form.first因为我在同一页上有这些表格的列表
它仍然不会提交。我有一种感觉,它没有正确地观看“.submittable”,因为我什至无法在单击复选框时收到闪烁的警报。
有什么指点吗?我忘记了什么吗?谢谢。
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 %>
最佳答案
您的代码似乎没有包含在对 $(document).ready()
的调用中,因此 jQuery 可能试图在您的复选框加载之前绑定(bind)事件。试试这个:
$(document).ready(function () {
$('.submittable').on('change', function() {
$(this).closest('form').submit();
});
});
关于javascript - Rails 表单不使用 ajax 提交更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26188642/