Yii - jQuery not working after renderPartial

Anand Sainath picture Anand Sainath · Feb 2, 2012 · Viewed 13.1k times · Source

I know this question has been asked numerous number of times, both here and in the Yii site, but I am not getting the solution even after going through each solution. I am sure I am doing something fundamentally wrong. So if you are still reading this - here goes nothing,

I have a page that has a CheckBoxList widget being loaded. It has a change() jQuery function call which refreshes a CGridView which works perfectly well. I also have a span related to each of the items in the checkBoxList which have a click event.

This click event, in turn calls a controller which "partially renders" a view -

Yii::app()->clientscript->scriptMap['jquery.js'] = false;


$this->widget('ext.xxx.EModelWidget', array(
'name' => $widget_name,
'manufacturer_id' => $manufacturer_id,
    )
);

And the corresponding widget code prints a CheckBoxList after fetching $data from the db.

echo CHtml::checkBoxList($this->name, array(), $data, array(
        'class' => 'modelFilter',
        'separator' => '',
        'template' => '<div>{input} {label}</div>',
        'id' => 'dummyID',
    ));

As you can see, I have put the class name for each element that will be rendered as a checkbox to be modelFilter

Now I have a script in the main view file to just display an alert box when the checkBox of class modelFilter is clicked.

Yii::app()->clientScript->registerScript('model-selected', "
$('input.modelFilter').change(function(){
  alert('Hellpo!');
  });
");

But unfortunately, this never happens.

The two common solutions which I have read in all the forums is

a) Yii::app()->clientscript->scriptMap['jquery.js'] = false; which you can see that I have duly followed.

b) $result and $processOutput parameters of the renderPartial to be false and true respectively., which is also something that I have followed.

So my question is what should I do to just get the change function on a content that is loaded via Ajax working, in Yii!!

Answer

marcovtwout picture marcovtwout · Feb 2, 2012

If I understand correctly, you are calling $('input.modelFilter').change() before you load the list of checkboxes. Used like that the event handler will not be bound to any elements inserted after the call.

You have to use delegated events instead of directly bound events. Take a look at: http://api.jquery.com/on/ (search for "Direct and delegated events")

$("body_or_input_container").on("change", "input.modelFilter", function(e){
    //callback
});