Need to set initial focus to a field on your form? This component is adapted from Fábio's code on the MonoRail forums.
namespace My.Product.Mvc
{
using Castle.MonoRail.Framework;
[ViewComponentDetails("InitialFocus")]
public class InitialFocusComponent : ViewComponent
{
private const string FOCUS_TEMPLATE =
"<script type=\"text/javascript\">Event.observe(window,'load',function(){{$('{0}').focus();}});</script>";
private string _id;
private bool _shouldRender;
[ViewComponentParam(Required=true)]
public virtual string Id
{
get { return _id; }
set { _id = value; }
}
public override void Initialize()
{
if( !Context.ContextVars.Contains("__Initial_Focus_Set__") )
{
Context.ContextVars["__Initial_Focus_Set__"] = Id;
_shouldRender = true;
}
}
public override void Render()
{
if( _shouldRender )
{
RenderText(string.Format(FOCUS_TEMPLATE, Id));
}
}
}
}
Use in your view like so:
<% component InitialFocus, {'id':'username'} %>
This component is "first in wins" meaning if you include multiple component references in the same view/subview, the first field specified will get initial focus. So far this has only been lightly tested on text fields.
posted @ Monday, June 25, 2007 10:41 AM