In my Ruby on Rails application, I have an index page with Ransack filtering. The Ransack form can be shown or hidden with an onclick event. My current code works fine, but once a search is executed in the form, the button goes back to "Show filters" although the form is already visible. How can I fix this to maintain its state after a search and retain functionality?
Here is the relevant HTML:
<div>
<p id="filterToggle" style="cursor: pointer;">Show filter</p>
<div id="filterForm" class="mb-2">
<%= search_form_for @q do |f| %>
<%= f.label :name_i_cont, "Filter by name" %>
<%= f.text_field :name_i_cont, :placeholder => "Enter a few characters" %>
<div>
<%= link_to "Clear filters", digs_path(@dig) %>
<%= f.submit :class => "btn btn-outline-secondary mt-2" %>
</div>
<% end %>
</div>
</div>
And here is my JavaScript function:
document.addEventListener('DOMContentLoaded', function() {
const filterToggle = document.getElementById('filterToggle')
const filterForm = document.getElementById('filterForm');
filterForm.style.display = 'none';
filterToggle.onclick = function() {
if (filterForm.style.display !== 'none') {
filterForm.style.display = 'none';
filterToggle.innerText = 'Show filter';
}
else {
filterForm.style.display = 'block';
filterToggle.innerText = 'Hide filter';
}
}
});
Thanks!