Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forms with Select2 are duplicated when clicking back button on browser in Rails 5

_header.html.erb (for forms part)

<%= form_for home_path, class: 'home', role: 'search', method: :get do |f| %>
<div class="form-group" style="display:inline;">
 <div class="input-group input-group-md">
 <%= text_field_tag :q, params[:q], placeholder: ... ,class: 'form-control hideOverflow', type: "search" %>
 <%= select_tag "category", options_from_collection_for_select(...),include_blank: true, class: 'form-control hideOverflow', type: "search" %>
 <%if logged_in? %>
  <%= select_tag "location", options_for_select([...], ...),class: 'form-control hideOverflow', type: "search" %>
 <% else %>
  <%= select_tag "location", options_for_select([...], ...),class: 'form-control hideOverflow', include_blank: true, type: "search" %>
 <% end %>
  <span class="input-group-addon"><%= submit_tag "Search", class: "btn-transparent"%></span>
 </div>
</div>
<% end %>

JS codes

<script>
 $( document ).on('turbolinks:load', function() {
    $('select#category').select2({ 
        width: '60%', 
        dropdownAutoWidth : true, 
        placeholder: "Choose a category",
        maximumSelectionLength: 3
    }); 
    $('select#location').select2({
        width: '40%', 
        dropdownAutoWidth : true, 
        minimumResultsForSearch: Infinity
    });
 });

</script>

Glitch or rendering issues (click links to view the images)

normal

after I click back button from the browser

Can someone help me out why? Plus, my search forms are in the navigation bar in header partial file.

If I get rid of $(...).select in the script, everything works fine... I think there is a problem with select.js

like image 465
Stephen Lee Avatar asked Jan 03 '17 11:01

Stephen Lee


1 Answers

Answered here: https://stackoverflow.com/a/41915129/5758027

I have use this solution in my own code:

    $(document).on('turbolinks:before-cache', function() {     // this approach corrects the select 2 to be duplicated when clicking the back button.
        $('.select-select2').select2('destroy');
        $('.select-search-select2').select2('destroy');
    } );

and an observer:

    $(document).ready( ready );                  //... once document ready
    $(document).ajaxComplete( ready );           //... once ajax is complete
    $(document).on('turbolinks:load', ready );   //... once a link is clicked

    function ready() {
        $(".select-search-select2").select2({
            theme: "bootstrap",
            language: 'es',
            allowClear: true
        });

        $(".select-select2").select2({
            theme: "bootstrap",
            language: 'es',
            minimumResultsForSearch: Infinity,
            allowClear: true
        });
    };
like image 198
Ángel Avatar answered Oct 12 '22 14:10

Ángel