How to trigger events (eg onkeyup) in ActiveForm elements

Hi guys.

I searched a lot on internet to solve this simple problem but could not get results. Then I would ask for help from you.I simply want to add a javascript function that runs when the onkeydown or onkeypress event is fired, but I do not want this moment to store this function in the file, I only run a javascript function directly.

Example

<? php echo $ form-> textField ($ model, ‘local’, array

(

‘onkeyup’ => ‘myfunctionjs();’

)

And later I would use functions in events that are stored in separate javascript.

How can I do this?

Thank You!

It’s better to NOT add attributes like onkueyup etc. in the CForm element but just an id :


<input id="foo">

Then (in the view) you register the script as follows :

(so Yii will auto-insert jQuery.js between <head> and </head>)




Yii::app()->getClientScript()->registerScript('myscript','$("#foo").keyup(function() {

  alert(\'Hello world !\');

});');

More events here:

http://api.jquery.com/category/events/keyboard-events/

I did the following in my view:

Yii::app()->getClientScript()->registerScript(‘myscript’,’$("#foo").keyup(function() {

alert(\‘Hello world !\’);

});’);

<div class="row" id="foo">

	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'observacao'); ?&gt;


	&lt;?php echo &#036;form-&gt;textArea(&#036;model,'observacao'); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'observacao'); ?&gt;

</div>

and it worked! But suppose I have more than one element within a div, how I would associate an id to the target element? And every time I want to handle an event I must assign an id to the div element that contains the target element? There is another way?

Thank you so much.

I did the following:

<?php echo $form->checkBox($model,‘justificar’,array

(

‘id’=>‘chk_just’

)

); ?>

now I have the id of the element to handle any events.

Thank you very much.

thanks … this post helped me too :)