Ajax Checkboxes

 

Ajaxify your checkboxes with jquery_ujs.

Code samples

<!-- app/views/todos/_todo.html.erb -->

<li id="<%= dom_id todo %>" class="todo">
  <%= check_box_tag dom_id(todo, :checkbox), nil, todo.completed?, data: { url: todo_toggles_path(todo), remote: :true, method: :post } %>

  <span class="name">
    <%= todo.name %>
  </span>

  <% unless todo.completed? %>
    <span class="actions">
      <%= link_to "Edit", edit_todo_path(todo), remote: true %> /
      <%= link_to "Delete", todo_path(todo), remote: true, method: :delete, data: { confirm: "Are you sure?" } %>
    </span>
  <% end %>
</li>

todos.coffee with bug:

# app/assets/javascripts/todos.coffee

$ ->
  $("input[type~=checkbox]").on "change", ->
    url = $(this).data("url")
    $.ajax(url, dataType: "script", method: "POST")

todos.coffee fixed:

# app/assets/javascripts/todos.coffee

$ ->
  $(document).on "change", "input[type~=checkbox]", ->
    url = $(this).data("url")
    $.ajax(url, dataType: "script", method: "POST")

Links