最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Forms with Select2 are duplicated when clicking back button on browser in Rails 5 - Stack Overflow

programmeradmin1浏览0评论

_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

_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

Share Improve this question edited Jan 3, 2017 at 21:15 Stephen Lee asked Jan 3, 2017 at 11:30 Stephen LeeStephen Lee 3273 silver badges10 bronze badges 8
  • I've used select2 before and never got this problem. Looks more like a rendering issue. I don't think you should worry about what users see if they press the back button after a form submission. There's always unwanted side effects after that. Does it happen even when you don't submit the form? – Nick Rameau Commented Jan 3, 2017 at 17:33
  • @NickRameau sup buddy! It does not happened when I submit the form... What I meant is whenever you click browser's back button (the forms will be in the header always, meaning it will be in every view), they are duplicated and looked like the picture in my post... I think it bothers a bit on UX... – Stephen Lee Commented Jan 3, 2017 at 20:30
  • I think turbolinks is the problem. I have problem with datatable, select2 and a datepicker js plugins. This happen with rails 5. – inye Commented Jan 10, 2017 at 18:33
  • @inye yeah...true :( thats what I was suspecting... Any suggestions how I should go around with Turbolinks?? Need help... – Stephen Lee Commented Jan 10, 2017 at 19:44
  • My last thought was do some like check if exist element (select2, datatable, etc) before create, if not exist -> create else -> do nothing. But I still do not try that solution. friday maybe I will try this. – inye Commented Jan 10, 2017 at 20:59
 |  Show 3 more comments

7 Answers 7

Reset to default 9

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
        });
    };

isn't clearing the cache all the time makes using turbolinks practically pointless?

how about something like this instead?

$(document).on('turbolinks:before-cache', function(e) {
  return $('.form-control.select2').each(function() {
    return $(this).select2('destroy');
  });
});

I wasn't able to solve this rendering issue (still waiting for the correct answer!) but if anyone has a similar problem like me, try thinking outside of box. Here is my hack: I added a back button in my applicaiton.

Get the full url path

# get the previous url 
def save_previous_page
    session[:return_to] = request.fullpath
end

Show the back button only if the page is NOT home page or search page

<% if session[:return_to] != request.fullpath%>
   <%= link_to session.delete(:return_to) || request.fullpath, class: 'back-button' do%>
     <i class="fa fa-arrow-circle-left" aria-hidden="true"></i>
   <%end%>
<% end %>

Meanwhile, I am still waiting and trying to fix rendering issue...

FIXED THE ISSUE

Simply add this code in your .js file

Turbolinks.clearCache();

Rails 7 Update

Many things here won't work in Rails 7 especially turbolinks:before-cache event. New event that you are looking for is turbo:before-cache, and turbo:load so it would look like this:

$(document).on("turbo:before-cache", function() {
    $("#select_id").select2('destroy');
});

$(document).on('turbo:load', function() {
    $('#select_id').select2();
});

Simple solution, don't run the select2 builder on stuff you would rather it not run on.

$("select#category:not(.select2-container):not(.select2-hidden-accessible)").select2();

This is most likely to be some asset inconsistency, you should check your app\views\layouts folder for files with duplicated declarations of wither jQuery, jQuery UJS or Turbolinks. Check all <script> tags of your pages, and if you are declaring both on layout folder and in internal views the same scripts. If that is not the case, check for render, yield or build calls

Im using rails 7, same issue occurred for me while using select2 along with tubrosteam.

$(document).on('turbo:before-cache', function (){
            select2Elements.forEach(function (selector){
                if ($(selector).data('select2')) {
                    $(selector).select2('destroy');
                }
            })
  })

(here select2Elements are array of id's(['#selector_1', '#selector_2',.... ]) which represents select2 field)

发布评论

评论列表(0)

  1. 暂无评论