Prabhu
Prabhu

Reputation: 57

Why my dropdown list is not showing in Select2?

Whenever i comment this script, select2 works perfectly but my other function are affected by commenting this code.

<script src="{{ asset('js/app.js') }}" defer></script>

This is my dropdown

<select class="roles form-control" name="roles[]" multiple="multiple">
 <option value="1">Admin</option>
 <option value="2">Agent</option>
 <option value="3">Customer</option>
 </select>
<script type="text/javascript">
    $(".roles").select2();
</script>

Select2 cdn link

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"> </script>

I am new to laravel and applying select2 for the first time. No idea where i went wrong.

Upvotes: 1

Views: 2099

Answers (1)

Anurat Chapanond
Anurat Chapanond

Reputation: 2987

It is to do with your javascript code triggers too early. Your code calls $(".roles").select2(); immediately even before the select element is created.

You should run the code when the page and elements are already created and ready which is triggered by document ready event.

In jQuery you can just write

$(document).ready(function() {
   .... your code here
});

or a shorthand

$(function() {
   .... your code here
});

So your code should look like

<script type="text/javascript">
$(function() {
    $(".roles").select2();
});
</script>

Upvotes: 1

Related Questions