最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set focus on an asp.net control on Page Load - Stack Overflow

programmeradmin2浏览0评论

I want to set focus on a control when page is loaded. I wrote this code but not working..

protected void setFocus(System.Web.UI.Control ctrl)
    {
        string s = "<SCRIPT language='javascript'>document.getElementById('" + ctrl.ID + "').focus() </SCRIPT>";
        Type csType = this.GetType();
        ClientScript.RegisterStartupScript(csType, "focus", s);
    }

and this line in PageLoad method:

this.setFocus(txtHeightfeet);

Please help.

EDIT:

This is HTML:

<input name="ctl00$MainContent$txtHeightfeet" type="text" maxlength="2" id="MainContent_txtHeightfeet" class="textEntry2" style="width:65px;" />

This is aspx code:

<asp:TextBox ID="txtHeightfeet" runat="server" CssClass="textEntry2" MaxLength="2" Width="65"></asp:TextBox>&nbsp;ft&nbsp;

and in code behind cs file, i declared it the same as you have mentioned.

I want to set focus on a control when page is loaded. I wrote this code but not working..

protected void setFocus(System.Web.UI.Control ctrl)
    {
        string s = "<SCRIPT language='javascript'>document.getElementById('" + ctrl.ID + "').focus() </SCRIPT>";
        Type csType = this.GetType();
        ClientScript.RegisterStartupScript(csType, "focus", s);
    }

and this line in PageLoad method:

this.setFocus(txtHeightfeet);

Please help.

EDIT:

This is HTML:

<input name="ctl00$MainContent$txtHeightfeet" type="text" maxlength="2" id="MainContent_txtHeightfeet" class="textEntry2" style="width:65px;" />

This is aspx code:

<asp:TextBox ID="txtHeightfeet" runat="server" CssClass="textEntry2" MaxLength="2" Width="65"></asp:TextBox>&nbsp;ft&nbsp;

and in code behind cs file, i declared it the same as you have mentioned.

Share Improve this question edited May 4, 2011 at 12:21 asma asked May 4, 2011 at 10:16 asmaasma 2,85516 gold badges64 silver badges88 bronze badges 1
  • possible duplicate of Set focus to textbox in ASP.NET Login control on page load – David d C e Freitas Commented Oct 25, 2013 at 1:12
Add a ment  | 

1 Answer 1

Reset to default 3

You should be able to just call the Focus() method of the control.

No need for that Javascript.

protected void Page_Load(object sender, EventArgs e)
{
    txtHeightfeet.Focus(); 
}
发布评论

评论列表(0)

  1. 暂无评论