Search code examples
jqueryyii2bundle

Yii2 Uncaught ReferenceError: $ is not defined


MyAssetset:

class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
    ];
    public $js = [
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
        'yii\web\JqueryAsset'
    ];
}

MyMain.php has register this asset:

AppAsset::register($this);

in my test.php use jquery

<div class="container">
<div class="row">
    <div class='col-sm-6'>
        <div class="form-group">
            <div class='input-group date' id='datetimepicker1'>
                <input type='text' class="form-control" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(function () {
            $('#datetimepicker1').datetimepicker();
        });
    </script>
</div>
</div>

Has this error:

Uncaught ReferenceError: $ is not defined

Hope you guys can help me out. Thanks!


Solution

  • You should use javascript scripts via assets or with method registerJs here is example

    <?php $this->registerJs('$(function () { $(\'#datetimepicker1\').datetimepicker();});', View::POS_END); ?>