[英]Rails form not submitting on change with ajax
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. 我正在开发一个带有ruby on rails的小型待办事项列表应用程序,当我选择一个复选框时,我想通过ajax提交表单。 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. 虽然更改复选框没有提交表单,所以我在SO上搜索了类似的问题,并对我的代码进行了一些更新。
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. 我有一种感觉,它没有正确地观看'.submittable',因为当点击一个复选框时我甚至无法获得闪光警报。
Any pointers? 有什么指针吗? Have I forgotten something? 我忘记了什么吗? Thanks. 谢谢。
index.html.erb 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 的application.js
$('.submittable').on('change', function() {
$(this).closest('form').submit();
});
update.js.erb 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. 您的代码似乎没有包含在对$(document).ready()
的调用中,因此jQuery可能会在您加载复选框之前尝试绑定事件。 Try this instead: 试试这个:
$(document).ready(function () {
$('.submittable').on('change', function() {
$(this).closest('form').submit();
});
});
You have to wait until the dom is loads 你必须等到dom加载
$(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 看到这一集的railscast,他正在解释你想做什么
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.