Yii 1.1: CGridView keep focus on the control after filtering


You can find the reason why I wrote this article here.

cursorEnd is an extra function that is used to place the cursor at the end of the text field, this can't be done in a cross-browser way without that function.

The first thing to do is register default handlers(filter change and afterAjaxUpdate) and register the cursorEnd function. You can add filter change event anywhere on the page.

// Configure all GridViews in the page
// Setup the filter(s) controls
function setupGridView(grid)
        grid = '.grid-view tr.filters';
    // Default handler for filter change event
    $('input,select', grid).change(function() {
        var grid = $(this).closest('.grid-view');
        $(document).data(grid.attr('id')+'-lastFocused', this.name);
// Default handler for beforeAjaxUpdate event
function afterAjaxUpdate(id, options)
    var grid = $('#'+id);
    var lf = $(document).data(grid.attr('id')+'-lastFocused');
    // If the function was not activated
    if(lf == null) return;
    // Get the control
    fe = $('[name="'+lf+'"]', grid);
    // If the control exists..
        if(fe.get(0).tagName == 'INPUT' && fe.attr('type') == 'text')
            // Focus and place the cursor at the end
            // Just focus
    // Setup the new filter controls
// Place the cursor at the end of the text field
jQuery.fn.cursorEnd = function()
    return this.each(function(){
        else if (this.createTextRange) {
            var range = this.createTextRange();
            range.moveEnd('character', this.value.length);
            range.moveStart('character', this.value.length);
        return false;

After that, add this property to your CGridView:


And that's it, you should still have the focus in the field after filtering ;)

Total 4 comments

#19139 report it
jayala at 2015/03/27 02:45pm
How to register this script

You may enclose it with "Yii::app()->clientScript->registerScript(" or with html script tag.

#19134 report it
Kavitama at 2015/03/26 06:19pm
How to register this script

Sorry for asking but do you enclose all this in a



#15956 report it
jayala at 2014/01/03 12:37pm
Where to put the handler code?

Put it before the Grid declaration and it should be fine.

#15954 report it
yii at 2014/01/03 10:39am
Where to put the handler code?

Hi, where I have to put the handler code?

Leave a comment

Please to leave your comment.

Write new article
  • Written by: jayala
  • Category: How-tos
  • Yii Version: 1.1
  • Votes: +6 / -1
  • Viewed: 11,773 times
  • Created on: Feb 22, 2012
  • Last updated: Mar 24, 2012
  • Tags: CGridView, filter