简体   繁体   中英

Set ACF select2 option via Javascript when using Ajax

I am trying to select an option in an Advanced Custom Fields select2 drop down that is lazy loaded by Ajax. The new Javascript API is very powerful, but I can't figure out how to set an option when Ajax is in play.

This works without Ajax, but not with:

var select = acf.getField('field_5c6ce2e0b5780');
select.select2.selectOption(7);

Anyone have any ideas how to make this work with Ajax?

After sifting through acf-input.js and also the Select2 documentation, I have found a way to do it using the addOption method. I'm not sure if this is a workaround, but it is working for my situation.

var select = acf.getField('field_5c6ce2e0b5780');
select.select2.addOption({
          id: 12345,
          text: 'New Option',
          selected: true
        });

This appears to be adding a new option to the list, but it doesn't override the option that is pulled from Ajax, so it works for my situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM