Abhishek Aravindan
Abhishek Aravindan

Reputation: 1482

Select2 not working without reloading the page

I have a issue with the Jquery select2 in Rails I have a model work in which days is a dropdown menu and i want to input values using Select2 Jquery.

below is days field _form.html.erb

  <div class="field">
<%= form.label :days %>
<%= form.select :days, options_for_select($days), options = {:multiple => true}, :id => "dropdown" %>

application.js

//= require jquery
//= require jquery_ujs
//= require select2-full
//= require activestorage
//= require turbolinks
//= require_tree .


  $(document).ready(function(){

    $( "#dropdown" ).select2({
        theme: "bootstrap"
    });
 });

The select2 works after reloading the the page, But not working if the page is redirected by link in navbar.

the navbar code below:

<nav>
 <div class="container">
  <ul class="main-menu">
   <li><%= link_to "Home", root_path %></li> 
   <li><%= link_to "new work", new_work_path %></li> 
  </ul>
 </div>
</nav>

application.html.erb:

<!DOCTYPE html>
 <html>
  <head>
   <title>Stack1</title>
   <%= csrf_meta_tags %>
   <%= csp_meta_tag %>
   <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
   <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>
  <body>
   <%= render 'layouts/navbar' %>
   <%= yield %>
  </body>
 </html>

the scenario is that user click new work in navbar and the new_work_path is displayed for input values, here the select2 not works, But after reloading the page the select2 works.

Any help is appreciated.

Upvotes: 1

Views: 1472

Answers (1)

Abhishek Aravindan
Abhishek Aravindan

Reputation: 1482

Finally found out solution for my question,I think the answer will help somebody who faces the same problem at research time. Instead of listening to event $(document).ready(function() , listen to event for $( document ).on('turbolinks:load', function() because rails use turbolinks. so we we should modify the code as:

$( document ).on('turbolinks:load', function() {
    $( "#dropdown" ).select2({
        theme: "bootstrap"
    });

Hope this will help for later same issue.

Upvotes: 4

Related Questions