title: How to set select2 ajax preselected value?
body: <p>Currently I followed <a href="https://stackoverflow.com/a/35514844/3297613">this</a> answer to make Ajaxselectmultiple field of Flask form to work. This works well with event create form. Like it automatically searches for the tag in backend through the api call.</p>
  
  <p>On update (update form invoked through js button click function), I want to display the preselected values. So I tried <a href="https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2" rel="nofollow noreferrer">this</a> solution given on their select2 official site, but I can't make it possible.</p>
  
  <p><code>forms.py</code></p>
  
  <pre><code>from flask_admin.model.fields import AjaxSelectMultipleField
  class EventCreateForm(FlaskForm):
      title = StringField(
          'Title',
          validators=[
              DataRequired(),
              Length(max=128),
          ],
      )
      start_date = DateField('Start Date', validators=[DataRequired(),])
      end_date = DateField('End Date', validators=[DataRequired(),])
      start_time = TimeField('Start Time', default=time())
      end_time = TimeField('End Time', default=time())
      location= StringField('Location')
      description = StringField('Description')
      tags = AjaxSelectMultipleField(
          loader=get_loader_by_name('tag')
      )
  </code></pre>
  
  <p><code>admin.py</code></p>
  
  <pre><code>class EventView(ModelView):
      can_create = False
      can_edit = False
      can_delete = False
      list_template = 'admin/events_list.html'
  
      def render(self, template, **kwargs):
              from teamup.forms import EventCreateForm
  
              kwargs.update(
                  {
                      'event_create_form': EventCreateForm(),
                      'tag_form': TagForm(),
                      'events_url': url_for('api.list_events'),
                      'current_user': flask_login.current_user
                  }
              )
              return super().render(template, **kwargs)
  </code></pre>
  
  <p><code>events.html</code></p>
  
  <pre><code>&lt;div class="row"&gt;
      &lt;div class="col-md-9"&gt;
          {{wtf.form_field(event_create_form.tags, class="form-control")}}
          &lt;/div&gt;
          &lt;div class="col-md-3"&gt;
          &lt;button type="button" class="btn btn-default" data-target="#createTagModal" data-toggle="modal"&gt;Create Tag&lt;/button&gt;
          &lt;/div&gt;
          &lt;/div&gt;
          {{wtf.form_field(event_create_form.description)}}
  </code></pre>
  
  <p><code>events.js</code></p>
  
  <pre><code>var calender = $('#calendar').fullCalendar({
          header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay,listWeek'
          },
          defaultDate: today,
          navLinks: true, // can click day/week names to navigate views
          weekNumbers: true,
          weekNumbersWithinDays: true,
          weekNumberCalculation: 'ISO',
          editable: true,
          eventLimit: true, // allow "more" link when too many events
          events: events_url,
          timezone: "America/Los_angeles",
          eventClick: function(event, element) {
            // reset form
            if($("#updateForm")[0] === undefined) {
              return;
            }
            $("#updateForm")[0].reset();
            $('#updateModal').modal('show');
            $('#updateForm input#id').val(event.id);
            $('#updateForm input#title').val(event.title);
            $('#updateForm input#location').val(event.location);
            $('#updateForm input#description').val(event.description);
            $('#updateForm input#interests').val(event.interests);
            $('#updateForm select#schools').val(event.school_id);
  
            var selinput = $('#updateForm input[data-json]')
            selinput.select2({
              ajax: {
                  url: '/admin/event/ajax/lookup/?name=tag'
              }
            });
            // // Fetch the preselected item, and add to the control
            var studentSelect = selinput;
            $.ajax({
              type: 'GET',
              url: '/admin/event/ajax/lookup/?name=tag&amp;query=cricket'
            }).then(function (data) {
              console.log(data);
              var val = data[0]
              var id = val[0]
              var text = val[1]
              // create the option and append to Select2
              var option = new Option(text, id, true, true);
              studentSelect.append(option).trigger('change.select2');
  
              // manually trigger the `select2:select` event
              studentSelect.trigger({
                  type: 'select2:select',
                  params: {
                      data: data
                  }
              });
            });
            //
            start_date = event.start.toDate();
            $('#updateForm #start_date').datetimepicker('update', new Date(start_date.getUTCFullYear(), start_date.getUTCMonth(), start_date.getUTCDate()));
            $('#updateForm #start_time').val(getValidTimeFormat(start_date))
            if(event.end) {
              end_date = event.end.toDate();
              $('#updateForm #end_date').datetimepicker('update', new Date(end_date.getUTCFullYear(), end_date.getUTCMonth(), end_date.getUTCDate()));
              $('#updateForm #end_time').val(getValidTimeFormat(end_date))
            }
          }
        });
  </code></pre>
  
  <p>manually filling the update form through js since the filled values should get changed based on the event in which the user clicks. </p>
  
  <p>The thing is, in all other answers they mentioned about adding <code>option</code> ele to  existing <code>select</code> element but in my case, there was not <code>select</code> tag exists instead I have one <code>input</code> tag and <code>ul</code>, <code>li</code> tags.</p>
  
  <pre><code>&lt;div class="form-group "&gt;&lt;label class="control-label" for="tags"&gt;Tags&lt;/label&gt;
        &lt;div class="select2-container select2-container-multi form-control" id="s2id_tags" style="width: 100%;"&gt;
       &lt;ul class="select2-choices"&gt;  
        &lt;li class="select2-search-choice"&gt;    
        &lt;div&gt;cricket&lt;/div&gt;    
        &lt;a href="#" class="select2-search-choice-close" tabindex="-1"&gt;
  &lt;/a&gt;
  &lt;/li&gt;
  &lt;li class="select2-search-field"&gt;    
  &lt;label for="s2id_autogen2" class="select2-offscreen"&gt;TagsTags&lt;/label&gt;    
  
  &lt;input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" class="select2-input" id="s2id_autogen2" placeholder="" style="width: 34px;" aria-activedescendant="select2-result-label-4"&gt;  
    &lt;/li&gt;
    &lt;/ul&gt;
    &lt;/div&gt;
    &lt;input class="form-control" data-json="[]" data-multiple="1" data-placeholder="Select a tag" data-role="select2-ajax" data-url="/admin/event/ajax/lookup/?name=tag" id="tags" name="tags" type="hidden" value="1" tabindex="-1" style="display: none;"&gt;
  
   &lt;/div&gt;
  </code></pre>
  
  <p>Note If I reinitialise the same input ele with select2 (<code>selinput.select2({</code>), existing ajax select is not working.</p>