Home > front end >  Reloading Select2 jQuery After AJAX Submission
Reloading Select2 jQuery After AJAX Submission

Time:10-22

I have a form that uses a Select2 multiple-selection field that is initialised like this:

jQuery(document).ready(function() {
  jQuery('#cred_form_1283_1_1_select-children').select2({
  dropdownParent: '#addChildModal',
  multiple: 'true',
  placeholder: 'Select Child(ren)'
  });
});

This works perfectly:

enter image description here

After an ajax submission or validation the Select2 doesn't load back into the form:

enter image description here

After reading numerous posts about this, I still cannot get it to work. Example post:

https://stackoverflow.com/a/21664216

I know you're supposed to reload it with an on() event handler, which I have tried in numerous ways, like this:

jQuery(document).ready(function(){
  jQuery('#cred_form_1283_1_1').on('change','#cred_form_1283_1_1_select-children', function(){
    //alert('OK!');
    jQuery(this).select2({
      dropdownParent: '#addChildModal',
      multiple: 'true',
      placeholder: 'Select Child(ren)'
    });
  });
});

With the #cred_form_1283_1_1 being the form ID, I have also tried this with document and neither work.

The on() is working as the commented alert box will trigger when the Select2 is updated, but the Select2 itself will not reload at all.

Can someone please point out the error here.

CodePudding user response:

Turns out the issue WAS related to the Toolset plugins. I found a hook called cred_form_ready in their code that isn't documented, but if you use that then whenever the form is ready it works.

jQuery(document).on( 'cred_form_ready', function($) {
  jQuery('#cred_form_1283_1_1_select-children').select2({
    dropdownParent: '#addChildModal',
    multiple: 'true',
    placeholder: 'Select Child(ren)'
  });
});

This reloads the jQuery whenever any AJAX call is made and runs every time perfectly.

  • Related