Support

Account

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