Search code examples
javascriptjqueryruby-on-railsajaxransack

rails ransack checkbox filter with ajax


I am using the ransack gem in my rails app. I have been able to implement a search feature with ajax in my views. I want to do something similar with checkbox filters. So essentially when a user clicks on the checkbox, it should display results immediately without the user having to click the submit button. Currently, the filter checkbox works fine with the submit button but I have no idea what jquery code i need to use to make it filter with ajax. This is my index.html with the ransack filter

<% new_roles = [] %>
<%= search_form_for @search, :class => 'filters_click' do |f| %>
  <% @jobs.each do |job| %>
  <% new_roles << job.role %>
<% end %>

  <% new_roles.uniq.each do |new| %>
    <%= check_box_tag('q[role_eq_any][]', new) %>
    <%= new %>
  <% end %>
  <%= f.submit "Search" %>
<% end %>
<div class="jobs"><%= render 'jobs' %></div>

This is my index.js

$(".jobs").html("<%= escape_javascript(render("jobs")) %>");

I would like to know what jquery code to write in my js so I can use Ajax to provide filter results when the user clicks on the checkbox.


Solution

  • You need to do the Ajax request when the checkbox is clicked, like this:

    $('input[type="checkbox"]').change(function() {
      alert ("Checkbox " + this.id + " clicked.");
    
      $.ajax({
        url: "your-query-url",
        data: $(".filters_click").serialize();
      });
    });
    

    But I think the easiest way to do it, it's to add remote: true to the form, and then just make the submit of the form with jQuery:

    $('input[type="checkbox"]').change(function() {
      $(".filters_click").submit();
    });