C# .NET - Focus is not working I tried even through javascript Please help me

Asked By Myla Rajani on 13-Jun-12 07:53 AM
Hi All,

I need to focus a textBox While page loads.
txtbox.Focus()  is not working and I even tried through javascript some times it is working sometimes it is not.....


Please help me in this.

Thanks in Advance
 

Chintan Vaghela replied to Myla Rajani on 13-Jun-12 07:54 AM

Hi Frndz,

 

Functionality: Set Focus on Control Using javascript    

 

Use focus as following way

 

Logic:

 

<script type="text/javascript" language="javascript">

 

 

    function validate() {

     

      var txtName = document.getElementById("<%= txtName.ClientID %>");

      txtName.focus();

    }

</script>

 

Hope this helpful!

Thanks

 

 

 

Myla Rajani replied to Chintan Vaghela on 13-Jun-12 08:03 AM


Thanks for your quick response But  it's not working
 
For the first time page loads it just focussed the control and went away Even it is very difficult to check whether its getting focussed or not...
TSN ... replied to Myla Rajani on 14-Jun-12 12:29 AM

Hi..

 

This is simple , just Add onLoad to the body tag and just make the textbox focus logic ..

 

<BODY onLoad="document.getElementById('txtUserName').focus();">

Jitendra Faye replied to Myla Rajani on 14-Jun-12 01:26 AM
Ok, Now write your code in server side-

protected void Page_Load(object sender, EventArgs e)
    {
      TextBox1.Focus();
    }


Try this and let me know.
Myla Rajani replied to TSN ... on 14-Jun-12 02:02 AM


Thanks for ur reply

But here, this page inherits Master Page,so i cant use body tag there
Myla Rajani replied to Jitendra Faye on 14-Jun-12 02:02 AM


Thanks Vickey.... But its not working here
TSN ... replied to Myla Rajani on 14-Jun-12 09:00 AM

Hi..

If you are inheriting the page from a master page then in the page load of the Content page find the body control of the master page and attach the onload function to it ..

Here is the sample just try with this…

Master Page Body Tag

<body id="MainBody" runat="server">

In the Content page where you want to make the textbox focus

protected void Page_Load(object sender, EventArgs e)

{

      HtmlGenericControl body = this.Master.FindControl("MainBody") as HtmlGenericControl;

 

      body.Attributes.Add("onLoad", " document.getElementById('txtUserName').focus();");

}

 

This should get you out of the problem.

Myla Rajani replied to TSN ... on 15-Jun-12 06:10 AM
Thank you  TSN.............
 
But the focus is not holding.For the first time it just blinked and went away.......



TSN ... replied to Myla Rajani on 15-Jun-12 07:45 AM
hi..

cehck if you are running any javascript fucntions
Myla Rajani replied to TSN ... on 22-Jun-12 08:06 AM
no