javascript - Rails 表单不使用 ajax 提交更改

标签 javascript jquery ruby-on-rails ruby ajax

我正在使用 ruby​​ on rails 开发一个待办事项列表小应用程序,我想在选中复选框时通过 ajax 提交表单。我一直在关注this guide尝试并做到这一点。

更改复选框并没有提交表单,所以我在 SO 上搜索了类似的问题并对我的代码进行了一些更新。

  1. 使用on() instead of live()
  2. 提交 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/

相关文章:

javascript - 如何垂直对齐颜色框中的文本?

ruby-on-rails - 销毁 rails 中的所有 Controller Action

javascript - 调用函数而不将其结果分配给变量

javascript - 在表单中输入信息,通过 jquery 调用时

python - 如何从Python中的JSON对象获取数据数组?

ruby-on-rails - 测试打印 Action

ruby-on-rails - Windows 上的 Hiredis 0.5.2

javascript - IE 11 中的渲染 react 应用程序给了我 "you need to enable javascript to run this app"

javascript - 将模块与 webpack 一起使用

javascript - ASP MVC javascript 延迟加载