You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bootstrap模态框中Select2点击选项后消失问题求助(Ajax数据源)

Fix: Select2 Ajax dropdown disappears after selecting an option in Bootstrap Modal

Hey there, I've run into this exact issue before when using Select2 4.x inside Bootstrap modals with Ajax data sources. Let's break down why this is happening and how to fix it, since you're using jQuery 1.11.1 and CodeIgniter.

What's Causing the Problem?

You already set dropdownParent: $("#modal_form") which is the right first step, but two key issues are likely at play here:

  • Select2 initializes too early: If you initialize Select2 before the modal is fully rendered, the DOM bindings get messed up
  • Autofocus conflict: The autofocus attribute on your select element clashes with Bootstrap's modal focus handling, causing the select box to vanish after selection

Step-by-Step Fix

1. Initialize Select2 after the modal is fully shown

Move your Select2 initialization code into Bootstrap's shown.bs.modal event callback. This ensures the modal's DOM is fully loaded before we attach Select2.

2. Remove the conflicting autofocus attribute

Instead of relying on the HTML autofocus attribute, manually set focus on the Select2 element once the modal is open.

3. Clean up Select2 when the modal closes

If you open the modal multiple times, you'll end up with duplicate Select2 instances unless you destroy the plugin when the modal hides.

Modified Code

View (Adjustments marked)

<!-- Modal Tambah -->
<div aria-hidden="true" aria-labelledby="myModalLabel" tabindex="-1" role="dialog" id="modal_form" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
<h4 class="modal-title"></h4>
</div>
<form action="#" id="form" class="form-horizontal">
<!-- <input type="hidden" value="" name="id"/> -->
<div class="modal-body form">
<div class="form-body">
<div class="form-group">
<label class="col-lg-3 col-sm-2 control-label">Tindakan Item</label>
<div class="col-lg-9">
<!-- Removed autofocus attribute -->
<select name="tindakan_item_id" id="tindakan_item_id" class="select_tindakan_id form-control"></select>
<span class="help-block"></span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="layanan_pemeriksaan_id" value="<?php echo $layanan_id; ?>">
<input type="hidden" name="layanan_tindakan_pasien_id" value="<?php echo $layanan_id; ?>">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- END Modal Tambah -->

JavaScript (Updated initialization logic)

// Initialize Select2 only after the modal is fully visible
$('#modal_form').on('shown.bs.modal', function () {
    $('.select_tindakan_id').select2({
        placeholder: '--- Silahkan Pilih ---',
        dropdownParent: $("#modal_form"),
        width: '100%',
        ajax: {
            url: '<?php echo site_url('perawatan/layanan_tindakan_pasien_/search_tindakan'); ?>',
            dataType: 'json',
            delay: 250,
            processResults: function (data) {
                return { results: data };
            },
            cache: true
        },
        minimumInputLength: 2
    });
    // Manually set focus on Select2
    $('.select_tindakan_id').focus();
});

// Destroy Select2 when modal closes to prevent duplicate instances
$('#modal_form').on('hidden.bs.modal', function () {
    $('.select_tindakan_id').select2('destroy');
});

Controller (No changes needed, just confirm output format)

public function search_tindakan() {
    $json = [];
    $this->load->database();
    if(!empty($this->input->get("q"))){
        $this->db->like('nama', $this->input->get("q"));
        $query = $this->db->select('id,nama as text,tindakan_id')
                        ->limit(10)
                        ->get("tindakan_item");
        $json = $query->result();
    }
    echo json_encode($json);
}

Quick Notes

  • The destroy step is crucial: Without it, repeated modal opens will create multiple Select2 instances attached to the same element, leading to weird bugs
  • Your CodeIgniter controller is already returning the correct JSON format (each item has id and text), which Select2 requires for Ajax sources
  • jQuery 1.11.1 is compatible with Select2 4.0.5, so no issues there

内容的提问来源于stack exchange,提问作者jharrvis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:56:52