[英]Rails form not submitting on change with ajax
我正在开发一个带有ruby on rails的小型待办事项列表应用程序,当我选择一个复选框时,我想通过ajax提交表单。 我一直在按照本指南尝试这样做。
虽然更改复选框没有提交表单,所以我在SO上搜索了类似的问题,并对我的代码进行了一些更新。
它仍然不会提交。 我有一种感觉,它没有正确地观看'.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可能会在您加载复选框之前尝试绑定事件。 试试这个:
$(document).ready(function () {
$('.submittable').on('change', function() {
$(this).closest('form').submit();
});
});
你必须等到dom加载
$(function(){
$('.submittable').on('change', function() {
$(this).closest('form').submit();
});
});
然后确保在控制器更新操作中
respond_to do |format|
if @object.update(object_params)
.
.
format.js
else
.
.
end
end
看到这一集的railscast,他正在解释你想做什么
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.