如何设置select2 ajax预选值?

Posted

技术标签:

【中文标题】如何设置select2 ajax预选值?【英文标题】:How to set select2 ajax preselected value? 【发布时间】:2019-01-15 04:40:18 【问题描述】:

目前我按照this 的回答使 Flask 表单的 Ajaxselectmultiple 字段工作。这适用于事件创建表单。喜欢它通过api调用自动在后端搜索标签。

更新时(通过 js 按钮单击功能调用更新表单),我想显示预选的值。所以我尝试了他们 select2 官方网站上给出的this 解决方案,但我无法做到。

forms.py

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')
    )

admin.py

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)

events.html

<div class="row">
    <div class="col-md-9">
        wtf.form_field(event_create_form.tags, class="form-control")
        </div>
        <div class="col-md-3">
        <button type="button" class="btn btn-default" data-target="#createTagModal" data-toggle="modal">Create Tag</button>
        </div>
        </div>
        wtf.form_field(event_create_form.description)

events.js

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&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))
          
        
      );

通过js手动填写更新表单,因为填写的值应该根据用户点击的事件而改变。

问题是,在他们提到的所有其他答案中,他们提到了将 option ele 添加到现有的 select 元素,但在我的情况下,不存在 select 标签,而是我有一个 input 标签和 ul , li 标签。

<div class="form-group "><label class="control-label" for="tags">Tags</label>
      <div class="select2-container select2-container-multi form-control" id="s2id_tags" style="width: 100%;">
     <ul class="select2-choices">  
      <li class="select2-search-choice">    
      <div>cricket</div>    
      <a href="#" class="select2-search-choice-close" tabindex="-1">
</a>
</li>
<li class="select2-search-field">    
<label for="s2id_autogen2" class="select2-offscreen">TagsTags</label>    

<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">  
  </li>
  </ul>
  </div>
  <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;">

 </div>

注意如果我用 select2 (selinput.select2() 重新初始化相同的输入 ele,现有的 ajax 选择将不起作用。

【问题讨论】:

【参考方案1】:

我通过将 json 对象设置为 select2 data 属性的值来实现,

$("#updateForm input[data-json]").select2("data", [id: "CA", text: "California",id:"MA", text: "Massachusetts"]);

【讨论】:

以上是关于如何设置select2 ajax预选值?的主要内容,如果未能解决你的问题,请参考以下文章

Select2 ajax:在编辑模式下预选数据

如何在 select2 多选中预选值?

jquery Select2 Ajax - 如何设置值(initSelection)

select2 和远程数据:预设值和文本避免服务器往返

如何在 laravel 中使用 AJAX 数据时设置 Select2 的选定值?

如何设置 jQuery Select2 的选定值?