CGridView keep focus on the control after filtering

You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#4) »

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.

// Default handler for filter change event
$(function(){
	$('input,select', '.grid-view tr.filters').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!=null)
	{
		if(fe.get(0).tagName == 'INPUT' && fe.attr('type') == 'text')
			// Focus and place the cursor at the end
			fe.cursorEnd();
		else
			// Just focus
			fe.focus();
	}
}

// Place the cursor at the end of the text field
jQuery.fn.cursorEnd = function()
{
	return this.each(function(){
		if(this.setSelectionRange)
		{
			this.focus();
			this.setSelectionRange(this.value.length,this.value.length);
		}
		else if (this.createTextRange) {
			var range = this.createTextRange();
			range.collapse(true);
			range.moveEnd('character', this.value.length);
			range.moveStart('character', this.value.length);
			range.select();
		}
		return false;
	});
}

After that, add this property to your CGridView:

'afterAjaxUpdate'=>'afterAjaxUpdate',

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

5 0
10 followers
Viewed: 17 458 times
Version: Unknown (update)
Category: How-tos
Written by: jayala
Last updated by: jayala
Created on: Feb 22, 2012
Last updated: 12 years ago
Update Article

Revisions

View all history

Related Articles