I need to change the multiple selection Select2 field on a front-end ACF form.
So when a user selects a value on another dropdown, the Select2 field should be populated with an ajax response. I managed to change the input[type=”hidden”] as well as select field of the target ACF field’s box. Then I called trigger(‘change’), on both fields, but nothing happened with the Select2. I also tried ‘change.select2’, also nothing happened.
Hi @isvaljek
There’s a good tutorial on how to do it here: http://www.bobz.co/dynamically-populate-select-fields-choice-in-advanced-custom-fields/. I’m not sure if this will work with the current version of ACF, but I guess you can try it.
I hope this helps 🙂
My problem here is with jQuery Select2 fields, I already managed to populate the underlying regular select field, but can’t seem to trigger the change so the jQuery Select2 box acknowledges the changes.
Hi @isvaljek
It’s possible that the issue occurred because the elements were loaded by AJAX, so it’s not recognized by your function. For something like that, you need to use the on() function instead. This page should give you more idea about it: https://select2.github.io/examples.html#events.
Also, please take a look at this page to learn more about this issue: http://stackoverflow.com/questions/6658752/click-event-doesnt-work-on-dynamically-generated-elements.
If the issue persists, could you please ask it to Select2 community instead?
I hope this makes sense 🙂
In the end I found the ‘data’ argument of select2 method.
So i did this:
$acf_row.find(‘[data-name=”sq_solution_features”] input[type=”hidden”]’).select2(‘data’, new_select2_data);
new_select2_data should be array of objects {id: id, name: name}
And it seems to work and persist through form submits.