Setting Focus on a Visual Studio WebControl
(or any other HTML element)
|
Scenario:
|
| |
You'd think it'd be easy to set focus on a particular control on a web
page...
Just set some property on the control, right? Arrrgh!
Grasshopper, it's not as straight forward as you might think;
You'll need a properly-placed snippet of javascript.
|
This Tip Presumes:
|
| |
- You're developing Asp.NET web pages
- You're using the Visual Studio IDE
- You're tyring to set focus on a WebControl
|
The javascript Snippet:
|
</form>
<script
type="text/javascript"
language="javascript">
document.getElementById("YourControlName").focus();
</script>
</body>
|
| |
Ensure the following:
- The javascript is placed after the close form tag
- The javascript is placed before the close body tag
- The @Page Directive SmartNavigation is not set to true
- The YourControlName highlighted above is replaced with your control's ID
value
|
If Your WebControl is Childed Within Web User Control:
|
| |
When you want to set focus on a control that is childed within a Web User
Control, things get a little trickier...
- Visual Studio will render the control with concatenated name
- The name is typically WebUserControlName_WebControlName
- Before attempting to set focus, render the page and...
- Use View Source to determine the name assigned to the control
- Set the YourControlName highlighted above with the concatenated control
name
|
Worth Note:
|
| |
You can also use this approach to set focus on simple HTML Elements, outside the
context of Visual Studio...
|