<body><script type="text/javascript"> function setAttributeOnload(object, attribute, val) { if(window.addEventListener) { window.addEventListener('load', function(){ object[attribute] = val; }, false); } else { window.attachEvent('onload', function(){ object[attribute] = val; }); } } </script> <div id="navbar-iframe-container"></div> <script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script> <script type="text/javascript"> gapi.load("gapi.iframes:gapi.iframes.style.bubble", function() { if (gapi.iframes && gapi.iframes.getContext) { gapi.iframes.getContext().openChild({ url: 'https://www.blogger.com/navbar.g?targetBlogID\x3d13376580\x26blogName\x3dThe+GeekWithin\x26publishMode\x3dPUBLISH_MODE_BLOGSPOT\x26navbarType\x3dBLUE\x26layoutType\x3dCLASSIC\x26searchRoot\x3dhttps://geekwithin.blogspot.com/search\x26blogLocale\x3den_US\x26v\x3d2\x26homepageUrl\x3dhttp://geekwithin.blogspot.com/\x26vt\x3d-8111287070889316650', where: document.getElementById("navbar-iframe-container"), id: "navbar-iframe" }); } }); </script>

The GeekWithin

Tuesday, June 07, 2005

Javascript element.focus() and ASP.NET

I'm not sure how many of you have run into this problem, but here it is in a nutshell.

Let's say you want to have a form load (web page) but want to specify which textbox, or other form element, has the focus. How would you do that from the code behind file?

You can't.

I know, how dumb. To make matters worse, it isn't like you can just create a javascript block and say:

Why not? Because .NET will change the reported name of your form element in many cases.... such as when you use User Controls. Yep, that's right. Not only does it rename it, but it gives it a name like ctl0_[yourname]. Yuck.

So, what is the solution? Since I just had to work this out, here is what I came up with. [Be aware that I use the QueryString or Form to pass the element to focus on. This could be easily changed to using control properties, I just didn't need to]:

On the parent (first) page, add a javascript block like this:
var elementFocus = "<%=elementFocus%>";
if (elementFocus != "")
document.Form1.elementFocus.setSelectionStart(0,0); //my pref

In the parent code behind, create a public string named elementFocus and set it to the Querystring and/or the Form objects value for the focus key.

Now, on the page WITH the form element you wish to focus, which may be the parent or an added user control, create a variable that you assign the all important property to.... ClientId. ClientId is the actual name that ASP.NET plans to name your form field based on what it current knows is being rendered. By grabbing this value and passing it via the QueryString/Form/Property value, you now know the name to set focus to.

That's it. If you want a more complete code sample, just let me know.


Creative Commons License  This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.