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...
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);
});
");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With