1

I am using jQuery select2 inside a modal... but its appearance is not right... u can see it in the below image... How to fix this ? Problem happens only inside modal.image

<div class="col">
   <label class="control-label">Department*</label>
      <select class="form-control select2" name="department_id">
         <option value="" selected>Select Department</option>
             @foreach ($departments as $value)
                <option value="{{ $value->id }}">{{ $value->name }}</option>
             @endforeach
     </select>
</div>

Jquery used for modal,

function viewCreate() {
        if (typeof device !== 'undefined')
            device.abort();
        device = $.ajax({
            type: 'GET',
            url: "devices/create/",
            dataType: 'JSON',
            async: true,
            beforeSend: function () {
                if (typeof device !== 'undefined')
                    device.abort();
            },
            success: function (response) {                   
                $('#showData').html(response.data);
                $('.showModal').modal('show');
            }
        });
    }
Rahul
  • 35
  • 5

2 Answers2

1

The issue is because the Select2 library is being instantiated on the content of the modal before it's visible in the DOM. As such, it causes rendering issues as the space used by the elements cannot be calculated accurately.

To fix this you can hook to the shown.bs.modal event and initialise the Select2 elements after the modal is visible:

// outside the AJAX call:
$('.showModal').on('shown.bs.modal', e => {
  $(e.target).find('.select2').select2({ /* your config options here... */ });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

You need to call your select2 in js file like this:

$(document).ready(function() {
    $('#department_id').select2();
});

I am not sure this is your problem but I hope it works for you.

Mahdi
  • 206
  • 2
  • 14