Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to register a plain function through clientScript->registerScript in yii

Tags:

yii

I'm calling a simple javascript function via onchange

echo $form->dropDownList($model, 'job_title', $jobTypes, array('onchange'=>'jobTitle(this);')); ?>

Trying to register jobTitle via clientScript->registerScript

Yii::app()->clientScript->registerScript('jobTitle', "
    function jobTitle(e) {
        alert('e');
    }
");

Yet I'm getting an error that jobTitle is not defined...

like image 529
keeg Avatar asked Dec 11 '22 17:12

keeg


1 Answers

The Reason:

As the default position is CClientScript::POS_READY, the generated js is:

jQuery(function($) {
    // ... there could be some other yii scriptlets too ...
    function jobTitle(e) {
        alert('e');
    }
});

Which means your function jobTitle is available only within the jQuery(); function scope and not from outside it, and that's why you get the undefined error.

Solution 1:

If you use the positions : CClientScript::POS_HEAD or CClientScript::POS_BEGIN or CClientScript::POS_END with your registerScript call, i.e:

Yii::app()->clientScript->registerScript('jobTitle', "
    function jobTitle(e) {
        alert('e');
    }
", CClientScript::POS_END);

the function will be defined outside, and in the global scope, and then you will be able to use the function.

Solution 2:

Alternatively if you need the function within ready(), i.e within jQuery(function($){});, you can define the function in the global window object, and still access it from outside:

Yii::app()->clientScript->registerScript('jobTitle', "
    window.jobTitle = function jobTitle(e) {
        alert('e');
    }
");

Solution 3:

Or you can simply add an event handler from jQuery itself, instead of doing it inline in the html:

Yii::app()->clientScript->registerScript('jobTitle', "
    $('body').on('change', 'id-of-job-title-input', function(e){
        console.log(e);
    });
");
like image 189
bool.dev Avatar answered May 06 '23 09:05

bool.dev