Select2 does not work on my pc but works on jsfidle

0

This code is in jsfidle, that is, it shows the stylized select and select it with an input search.

    <html>
            <head>
                <title>TESTE</title>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/i18n/pt-BR.js"></script>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.js"></script><scriptlanguage="JavaScript">
                    $('.multiplo').select2({
                        placeholder: 'selecione'
                    });
                </script>

                <style type="text/css">
                    .multiplo{
                        width:50%;
                    }
                </style>
            </head>


            <body>

            <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css" rel="stylesheet"/>

            <select class="multiplo" name="" multiple="multiple">
                <option>Um</option>
                <option>Dois</option>
                <option>Três</option>
                <option>Quatro</option>
            </select>



            </body>
            </html>

But when I get this code and play in a .php file on localhost it does not work.

As it appears when I run in jsfidle:

NowasitappearswhenIruninlocalhost:

Doesanyoneknowwhatmightbecausingthis?

Insourcesinthechromeconsoleitlookslikeitloadsboth.cssand.js

EDIT

Consoletab

    
asked by anonymous 06.02.2018 / 02:00

1 answer

2

You can only access page elements after they are fully loaded.

To do this place your code inside:

$( document ).ready(function() {
    //aqui
});

Or in its most compact and common form:

$(function() {
    //aqui
});

Applying to your code would look like this:

$(function() {
    $('.multiplo').select2({
        placeholder: 'selecione'
    });
});

In JSFiddle you do not need to have this because the platform itself only executes the javascript block after the html and css is loaded. The same happens in the live snippets of StackOverflow.

Documentation for the JQuery document ready

    
06.02.2018 / 02:19