'Adding and selecting an option when using an Ajax data source and templateSelection

I have the following problem to which I can't find a solution. I am using select2 with an ajax data source and templateSelection so I can populate more fields. This works fine.

I want to add a button which programmatically adds and selects a value, unfortunately this does not work. Only if I deactivate templateSelection, it works. Also the other values (firstname, lastname, email) are filled in after the second click of the button.

Here is my code: https://plnkr.co/edit/eVGTJwAr4FcYCw6a

For better display I removed the select2-hidden-accessible class so you can see the options menu.

I really appreciate your help

Update: Somewhere on the internet I read that with templateSelection option.text must be returned, I changed that and now it works.

To the second problem: I had the idea to add a setTimeout, it works now, but I don't find it optimal. See second button. Code is updated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source