<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\x3dhttp://geekwithin.blogspot.com/search\x26blogLocale\x3den_US\x26v\x3d2\x26homepageUrl\x3dhttp://geekwithin.blogspot.com/\x26vt\x3d3997356767057402239', where: document.getElementById("navbar-iframe-container"), id: "navbar-iframe" }); } }); </script>

The GeekWithin

Friday, July 15, 2005

Making Things Focus

There are new challenges each and every day, and coming up with a consistent way to set Focus on a given form field is my new one. Of course, we can't leave things that way... so I now have a method to fix this problem.

The Javascript required was easy:

function setFocus()
{
//Notice the use of a Public variable
var formElement = "<%=formElement%>";

//We have to check and verify it equals something
if (formElement != "")
{
document.forms[0][formElement].focus();
document.forms[0][formElement].setSelectionRange(0,0);
}
}


See, rather easy. To make it run in the page all you do is add the onLoad attribute to the body tag like this: onload="setFocus()"

Now that your page is ready, it is time to add the pieces you need to the ASP.Net code behind file. You have a few options:

1. Set focus immediately on page load: formElement = object.ClientId
2. Set focus during an event handler - same as above
3. Set the button to be clicked to put the ClientId value into a hidden text field:
button.Attributes.Add("onmousedown", "document.forms[0].hiddentext.value =
'" + object.ClientID + "';")

Don't forget that objects contained within Web User Controls have "_ctl0_" appended to the
front of them.

I will post a demonstration later, any thoughts until then?


 

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