1

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.

What is the error here?

halfer
  • 19,824
  • 17
  • 99
  • 186
Feel Content
  • 117
  • 9
  • What is your ajax doing to that select? are you realoading parts of the HTML? maybe the full selects gets reloaded? – Diego Oct 17 '22 at 12:28
  • @Diego Honestly, I don't know. It's built through a suite of plugins called Toolset and all of that is handled behind the scenes. I have nothing influencing it except this. I have raised this with their support first and got told to go and look into this. Please see the thread here: https://toolset.com/forums/topic/reloading-select2-javascript-after-ajax-submission-validation/ – Feel Content Oct 17 '22 at 12:52
  • Reading your question again, it is submitting the form and then resetting it without reloading the page. – Feel Content Oct 17 '22 at 21:37

1 Answers1

0

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.

Feel Content
  • 117
  • 9