[英]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.