Ask a Jedi: Setting focus to a field inside cflayout - possible?

JC asks:

Have you had any success placing focus on a text field inside a cflayoutarea? Is this possible or am I chasing a red herring?

I had not tried this before, but it wasn’t too hard. First consider a simple CFLAYOUT page:

<cflayout type="border">

&lt;cflayoutarea position="left" align="center" 
		size="400" collapsible="true" title="Menu"&gt;
&lt;p&gt;
Menu 1
&lt;/p&gt;
&lt;p&gt;
Menu 2
&lt;/p&gt;
&lt;p&gt;
Menu 3
&lt;/p&gt;
&lt;/cflayoutarea&gt;

&lt;cflayoutarea position="center"&gt;
&lt;p&gt;
&lt;form id="someform"&gt;
&lt;input type="text" name="username" id="username"&gt;
&lt;/form&gt;
&lt;/p&gt;
&lt;/cflayoutarea&gt;

</cflayout> </code>

Notice I’ve placed a form inside the main layout box. I want to run code to set focus when the page loads, and ColdFusion provides a function for this - ajaxOnLoad():

<cfset ajaxOnLoad("setfocus")>

The code for setfocus is no different than any other JavaScript code to set focus:

<script> function setfocus() { var myfield = document.getElementById("username"); myfield.focus(); } </script>

The only thing to watch out for is that ajaxOnLoad is a bit picky. It requires your JS function to be inside <HEAD> tags. So a complete example would be:

<html> <head> <script> function setfocus() { var myfield = document.getElementById("username"); myfield.focus(); } </script> </head>

<body> <cflayout type=”border”>

&lt;cflayoutarea position="left" align="center" 
		size="400" collapsible="true" title="Menu"&gt;
&lt;p&gt;
Menu 1
&lt;/p&gt;
&lt;p&gt;
Menu 2
&lt;/p&gt;
&lt;p&gt;
Menu 3
&lt;/p&gt;
&lt;/cflayoutarea&gt;

&lt;cflayoutarea position="center"&gt;
&lt;p&gt;
&lt;form id="someform"&gt;
&lt;input type="text" name="username" id="username"&gt;
&lt;/form&gt;
&lt;/p&gt;
&lt;/cflayoutarea&gt;

</cflayout>

<cfset ajaxOnLoad(“setfocus”)>

</body> </html> </code>

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments