【问题标题】:select option of select2 was missing after submit the update and how to set the selected value from database提交更新后 select2 的选择选项丢失以及如何从数据库中设置选定的值
【发布时间】:2021-11-19 06:30:42
【问题描述】:

select2 有几个问题。首先,当我单击编辑按钮显示编辑模式时,select2的选择选项不显示数据库中的值。

这是编辑模式:

代码如下:

<script>
  // Edit
  $('body').on('click', '.edit', function (event) {
    event.preventDefault();
    let id = $(this).attr('id');
    $.get('/admin/diklat/diklats/' + id + '/edit', function (data) {
      $('#code').val(data.data.code);
      $('#name').val(data.data.name);
      $('#lesson_hour').val(data.data.lesson_hour);
      $('#department_id').val(data.data.department_id);
      $('#schema_code').val(data.data.schema_code);
      $('#committee').html('');
      for (let index = 0; index < data.committee.length; index++) {
          $('#committee').append(`<option selected value="${data.committee[index]}">${data.committee[index]}</option>`)
      }
      $('#id').val(data.data.id);
      $('#start_date').val(data.data.start_date);
      $('#end_date').val(data.data.end_date);
      $('#location').val(data.data.location);
      $('#regency_id').val(data.data.regency_id); // this is the part that cannot show its value
      $('#modal-diklat').modal('show');
    })
  });
</script>
<div class="row">
  <div class="col">
   <div class="form-group">
    <label class="form-label" for="regency_id">Kabupaten</label>
    <select id="regency_id" name="regency_id" class="select2 form-control">
      <option value=""></option>
      @foreach ($regencys as $regency)
      <option value="{{$regency->id}}">{{$regency->name}}</option>
      @endforeach
    </select>
   </div>
  </div>
</div>

第二个问题是当我点击更新按钮时,select2的选择选项丢失了。

这里:

当更新过程完成后(我想在不重新加载页面的情况下再添加一个数据),它仍然丢失,如上图所示。但是,当我重新加载页面时, 它像正常一样重新出现。

有人可以帮我解决这个问题吗?我一直在寻找解决方案,但不幸的是我仍然无法解决它

【问题讨论】:

  • 你需要在获取并分配$('select').select2()之类的数据后应用select2
  • 并在添加/发布数据后检查此链接 - stackoverflow.com/questions/17957040/…
  • @PHPGeek 哇哦。当我添加 $('select').select2();选择选项不再丢失。非常感谢您。但我仍然无法解决其他问题(设置从数据库获取的值)
  • 已解决。我只需要添加.trigger('change'); 就像:$('#responsible_person').val(data.data.responsible_person).trigger('change');
  • 我不知道您使用的是哪个版本的 select2。但你可以使用 $('#id").select2('val','your value')

标签: php jquery ajax jquery-select2


【解决方案1】:

解决了。对于第一个问题,只需要定义类似

$('select').select2();

第二期只需添加.trigger("change");

例子:

$('#regency_id').val(data.data.regency_id).trigger('change');

注意:OP 在问题部分提供答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 2014-10-10
    • 2016-03-14
    • 2013-03-01
    • 1970-01-01
    相关资源
    最近更新 更多