Home › Forums › Backend Issues (wp-admin) › Reload values in select2 with ajax › Reply To: Reload values in select2 with ajax
I found out that the select2 can be refreshed by calling the change.select2
.
var field = acf.getField('acf-field-key');
var $select = field.$el.find('select');
// Could also be jQuery collection, optgroup elements or HTML string if working
const newOptions = [
new Option('New label', 'new-value'),
new Option('Another option', 'another-value')
];
// Clear previous elements
$select.empty();
// Add new options to select element
$select.append(newOptions);
// Set a new selected option
$select.val('new-value');
// Refresh select2
$select.trigger('change.select2');
You can of course keep or alter previous elements, instead of removing them. I guess you could do pretty much anything before triggering the change.select2
event.
I hope the JavaScript API will update in the future to a non jQuery solution
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.