在onchange html值返回后,select2无法正常工作

问题描述 投票:1回答:1

我想基于另一个选择框生成select2下拉框。第一次发生变化时它工作正常,它会生成select2下拉框,但是当我想更改时间更多时,select2下拉框不起作用。

这是我的代码:

 <div class="col-sm-8">
            <select  class="question form-control search-select" name="question_id">
                <option value="">Please choice a question </option>
                @if(!empty($questions) && count($questions) > 0)
                    @foreach($questions as $question)
                        <option value="{{ $question->id }}" data-page-number="{{$question->question_page_no}}">{{$question->question_title}}</option>
                    @endforeach
                @else
                    <option value="">Data not found.</option>
                @endif
            </select>
        </div>

 <div class="form-group">
        <label class="col-sm-3 control-label" for="form-field-1">
            <strong>Answer</strong>
        </label>
        <div class="col-sm-8">
            <select id="answer" multiple="multiple" class="question-value answer-select" name="question_value">
            </select>
        </div>
    </div>

jQuery的:

$.ajax({
  type:"GET",
  url:site_url + '/admin/question/value/ajax/'+question_id,
  success: function (data) {
    $('.question-value').html(data);
    generateSelect2();
  },
});
function generateSelect2() {
  if($('.answer-select').length) {
    $('.answer-select').select2({
      allowClear: true,
      width: '100%',
      placeholder: "Please choice answer(s)"
    });
  }
}
javascript jquery html jquery-select2
1个回答
0
投票

你应该首先使用.select2('destroy')销毁它,然后将其初始化为新用途:

function generateSelect2() {
  if($('.answer-select').length) {
    $('.answer-select').select2('destroy').select2({
      allowClear: true,
      width: '100%',
      placeholder: "Please choice answer(s)"
    });
  }
}

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.