OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Select2 with ajax gets initialized several times with Rails turbolinks events

  • Thread starter Thread starter morismael
  • Start date Start date
M

morismael

Guest
I am a developing a Ruby On Rails app using Rails 4.2.6. I am using Turbolinks alongside jquery.turbolinks (sorry I could'nt post the links to those elements as I am a newbie on the site). My problem is very simple but I just can't solve it. Here it is: I have a form fetched through AJAX

Code:
<div class="card-footer">
  <a class="btn btn-sm btn-primary-outline" data-remote="true"  href="/profiles/Mke5kA/positions/new"><i class="fa fa-plus"></i> Nouvelle expérience professionnelle</a>
  <div id="new_position_form"></div>
</div>

The form contains Select2 elements that get their data through AJAX

Code:
= simple_form_for [profile, position], remote: true, html: {id: 'positionForm', class: 'm-b-1'} do |f|
  = f.input :company_id, as: :select, input_html: {:'data-behaviour' => 'company-select2', :'data-kind' => 'company'}
  = f.input :title
  = f.input :summary
  - location = f.object.build_location
  = f.simple_fields_for :location do |l|
    = render 'locations/fields', l: l, city: position.city
  = render "profiles/shared/date_fields", f: f, model: position
  = f.input :skill_list, as: :select, input_html: {multiple: true, :data => {:behaviour => 'acts-as-taggable', :'taggable-context' => 'skills'}}
  %button.btn.btn-primary{:type => "submit"}= icon('check-square-o', 'Enregistrer')
  = link_to icon('remove', 'Annuler'), 'javascript:void(0)', 
        data: {:'lgnk-behaviour' => "remove-form", :'lgnk-target' => "#positionForm" }, class: 'btn btn-secondary'
  • The Select2 elements are "activated" currently upon Rails Trubolinks events "page:load page:update", but I have also tried "page:change"
  • When the form is fetched: the select2 elements are fine (activated correctly):

Initial form (after AJAX fetch


My problem appears when I try typing in the Select2 that are using AJAX to get the data: all the select2s are duplicated:

enter image description here


Here is how I get the Select2 initialized:

Code:
var loc_tag = function() {
  $('[data-behaviour="acts-as-taggable"]').not('.select2-hidden-accessible').each (function (index, element) {
    if ($(element).data('value')) {
      var options = $(element).data('value').split(', ');
      $.each(options, function(key, tag){
        $(element).append($('<option selected></option>').val(tag).text(tag));
      });
    }

    $(element).select2({
      ajax: {
        url: "/tags?context="+$(element).data('taggable-context'),
        dataType: 'json',
        headers: {
         "Accept": "application/json"
        },
       delay: 250,
       data: function (params) {
         return {
           q: params.term, // search term
           page: params.page
         };
       },
       processResults: function (data, page) {
         return {
           results: data
         };
      },
      cache: true
    },
    escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
    minimumInputLength: 2,
    tags: true,
    language: "fr",
    theme: "bootstrap",
    width: "100%",
    placeholder: 'Mots clés...'
    });
  });

};
$(document).on('page:load page:update', loc_tag);

I want the Select2 elements to get initialized only once (when the form is fetched) and not upon AJAX responses on them getting their data. I have tried jQuery.not(".select2-hiden-accessible") on the elements unsing Select2 (select2-hidden-accessible being the class Select2 adds to an initialized Select2 element) but it does not work.

Many thanks for your kind help!

<p>I am a developing a Ruby On Rails app using Rails 4.2.6. I am using Turbolinks alongside jquery.turbolinks (sorry I could'nt post the links to those elements as I am a newbie on the site). My problem is very simple but I just can't solve it. Here it is:
I have a form fetched through AJAX</p>

<pre><code><div class="card-footer">
<a class="btn btn-sm btn-primary-outline" data-remote="true" href="/profiles/Mke5kA/positions/new"><i class="fa fa-plus"></i> Nouvelle expérience professionnelle</a>
<div id="new_position_form"></div>
</div>
</code></pre>

<p>The form contains Select2 elements that get their data through AJAX</p>

<pre><code>= simple_form_for [profile, position], remote: true, html: {id: 'positionForm', class: 'm-b-1'} do |f|
= f.input :company_id, as: :select, input_html: {:'data-behaviour' => 'company-select2', :'data-kind' => 'company'}
= f.input :title
= f.input :summary
- location = f.object.build_location
= f.simple_fields_for :location do |l|
= render 'locations/fields', l: l, city: position.city
= render "profiles/shared/date_fields", f: f, model: position
= f.input :skill_list, as: :select, input_html: {multiple: true, :data => {:behaviour => 'acts-as-taggable', :'taggable-context' => 'skills'}}
%button.btn.btn-primary{:type => "submit"}= icon('check-square-o', 'Enregistrer')
= link_to icon('remove', 'Annuler'), 'javascript:void(0)',
data: {:'lgnk-behaviour' => "remove-form", :'lgnk-target' => "#positionForm" }, class: 'btn btn-secondary'
</code></pre>

<ul>
<li>The Select2 elements are "activated" currently upon Rails Trubolinks events "page:load page:update", but I have also tried "page:change"</li>
<li>When the form is fetched: the select2 elements are fine (activated correctly):</li>
</ul>

<p><img src="https://i.sstatic.net/aSkjl.png" alt="Initial form (after AJAX fetch"></p>

<p>My problem appears when I try typing in the Select2 that are using AJAX to get the data: all the select2s are duplicated:</p>

<p><img src="https://i.sstatic.net/X25so.png" alt="enter image description here"></p>

<p>Here is how I get the Select2 initialized:</p>

<pre><code>var loc_tag = function() {
$('[data-behaviour="acts-as-taggable"]').not('.select2-hidden-accessible').each (function (index, element) {
if ($(element).data('value')) {
var options = $(element).data('value').split(', ');
$.each(options, function(key, tag){
$(element).append($('<option selected></option>').val(tag).text(tag));
});
}

$(element).select2({
ajax: {
url: "/tags?context="+$(element).data('taggable-context'),
dataType: 'json',
headers: {
"Accept": "application/json"
},
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
return {
results: data
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 2,
tags: true,
language: "fr",
theme: "bootstrap",
width: "100%",
placeholder: 'Mots clés...'
});
});

};
$(document).on('page:load page:update', loc_tag);
</code></pre>

<p>I want the Select2 elements to get initialized only once (when the form is fetched) and not upon AJAX responses on them getting their data. I have tried jQuery.not(".select2-hiden-accessible") on the elements unsing Select2 (select2-hidden-accessible being the class Select2 adds to an initialized Select2 element) but it does not work. </p>

<p>Many thanks for your kind help!</p>
 

Latest posts

Top