Uncaught TypeError: $(…).select2 is not a function

2020-02-14 18:17发布

I download the select2 package and include the two files select2.min.css and select2.min.js into my laravel public file, select2.min.css into public/css folder and select2.min.js into public/js folder And I want to do a multiple select on my page. Here is my "select" like:

 <select class="form-control js-example-basic-multiple" name="tags"         
     multiple="multiple"> 
    @foreach($tags as $tag)
       <option value='{{ $tag->id }}'>{{ $tag->name }}</option>
    @endforeach
 </select>*

And this is my <script> section:

<script  src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="{{ URL::to('js/select2.min.js') }}"></script></script>
<script>
        $(document).ready(function(){
            $(".js-example-basic-multiple").select2();
        });
</script>

I don't know the multiple select is not working and browser always show "Uncaught TypeError: $(...).select2 is not a function"

Has everyone met this problem before?

2条回答
你好瞎i
2楼-- · 2020-02-14 18:56

In the situation where you have no control of the ordering of the tags, or jQuery loads twice, eg you are a content editor:

// Concept: Render select2 fields after all javascript has finished loading
var initSelect2 = function(){

    // function that will initialize the select2 plugin, to be triggered later
    var renderSelect = function(){
        $('section#formSection select').each(function(){
            $(this).select2({
                'dropdownCssClass': 'dropdown-hover',
                'width': '',
                'minimumResultsForSearch': -1,
            });
        })
    };

    // create select2 HTML elements
    var style = document.createElement('link');
    var script = document.createElement('script');
    style.rel = 'stylesheet';
    style.href = 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css';    
    script.type = 'text/javascript';
    script.src = 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.full.min.js';

    // trigger the select2 initialization once the script tag has finished loading 
    script.onload = renderSelect;

    // render the style and script tags into the DOM
    document.getElementsByTagName('head')[0].appendChild(style);
    document.getElementsByTagName('head')[0].appendChild(script);
};

initSelect2();
查看更多
叛逆
3楼-- · 2020-02-14 19:03

Most possible reason is to load jQuery twice. The second time when jQuery loaded it removes registered plugins.

Solution is

  1. Script loading should be in corrected order. That is

    1. jQuery,
    2. select2,
    3. your js files
    
  2. jQuery should be loaded only once.

查看更多
登录 后发表回答