You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Getting Focused - and a Quick JavaScript Lesson

Getting Focused - and a Quick JavaScript Lesson

You visit a Web site that offers a form inviting you to enter some input. No big deal - we see them all the time, right?

But do you move your cursor to that first data entry area using the mouse? Or are you, like me, a keyboard maven - in which case you find that often you have to hit the tab key several times before you can enter data?

I've visited sites with navigational toolbars across the top and/or left side of the form - forcing me to tab dozens and dozens of times. It's an annoyance, especially if visitors to your site know the site designer could have easily prevented the problem.

There's an incredibly simple solution. Just the tiniest bit of JavaScript. A single line of code, really. This article will show you how...and will also lay the most basic foundation of using JavaScript if you're new to it.

Laying the Foundation
The technique we're talking about here involves putting the "keyboard focus" on whatever form input field - a text, password or textarea box or even a radio, checkbox or select field - you want the user to enter data into first. The solution is the JavaScript "focus" method.

The JavaScript language is available to any Web page designer. (Microsoft must refer to their version of the language, made popular by the Netscape browser, as JScript. They're nearly the same, especially for the purposes of this article.) It's a scripting language that can be used to add features to your Web page that aren't otherwise provided by HTML.

This article will show you the simplest application of this focus method. It's pretty straightforward and should work just fine in most instances. JavaScript is widely supported by most browsers now and this particular feature is also supported pretty much identically in both Netscape's and Microsoft's versions of the language, so there's no need to worry about it breaking on different browsers.

This built-in focus "method" is pretty much the same sort of thing as a function in ColdFusion - like now(). In fact, we'll even use it in a similar fashion, referring to it as "focus()" in our code.

Gimme the Goods
We need to put this method in some JavaScript code inside our page. If you haven't coded JavaScript on your pages, you need to know that there are several ways to cause JavaScript to be coded on a page. You can embed the code in a pair of <SCRIPT> tags (and even then you have choices about where those tags are placed) or you can place it in special attributes of HTML tags (such as ONLOAD within a <BODY> tag).

Let's take a simple example in just the first of those two forms. We can use the JavaScript alert() method to cause a message to be displayed to the user in a popup box. To do that, we could use the following code:

<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
alert('Hello World');

Put that code just about anywhere in an HTML page, and when you view that page in a browser you'll see a message pop up: "Hello World." Try it. We can use the same approach for specifying JavaScript code to indicate that we want to have the focus placed on a particular field. We're almost ready!

Whither the Form Field?
The focus() method operates on form fields. One of the many powers of JavaScript is that not only can we refer to all the elements of our page (all the forms, form fields, indeed every tag and its contents and attri-butes), we can manipulate them as well. How do we specify that we intend to work with some part of our page, such as a particular form field? Most of you will know that you can give a name to a form field, and in CF that will become the name of a form field on the form's action page. In our JavaScript we can use that same name to refer to the form field in order to give it focus. So if we have an input field for a "UserId" that should be entered, the HTML would be:

<FORM ->
Enter Userid: <INPUT TYPE="text" Name="UserId">

Of course, the <FORM> tag would be specified completely and there would be other form field information provided both before and after this input field. But it's important to know that this does indeed (and must) occur within a <FORM> tag.

One reason that's important (besides being the way HTML is coded!) is that when we want to refer to a particular element within a Web page from within JavaScript, we need to refer to it in the form of its relationship to the entire page. This input form field, "UserId", occurs inside of a form. So on a simple level, we would refer to it as form.UserId. This isn't technically correct, however, since it's possible to have more than one form in a page. We need instead to indicate the specific form in which the field occurs.

What's in a Name?
There are two ways to do this: we can refer to the form either by name or by indicating the relative location of the form on the page. Which will be appropriate for you depends on your situation. If you've specified a NAME attribute on the <FORM> tag, then you'd use that name.

If we had specified, for instance, NAME="Login" on the <FORM> tag, then we would refer to the form field as Login.Userid. But we're not done yet. The form itself occurs within the Web page, and while it mightn't seem necessary, the contents of the page are considered to be within the "document" on the page. (If you've heard of the Document Object Model, what we've been describing is part of that.) We finally have the complete means by which to refer to the field: document.Login.UserId.

Before leaving this subject, let's clarify that if you haven't named your form, you can still refer to it by indicating the relative location of the form within the document. There is a special "forms" array in every Web page document, so if you have only one form in yours, you would indicate it as the first form.

Unfortunately, even this can trip you up because in JavaScript (as in many languages) you start counting lists of elements at 0 rather than 1. So the way to refer to your form field (assuming it's within the only form on the page) would be:


Notice that this isn't used as "form[0]" but as "forms[0]". It's a subtle point, but again: if it's not specified correctly, you'll receive an error.

We're on the Case
It's critically important to remember that JavaScript is case-sensitive. The case you choose when you name something yourself must be the case you use when referring to it later with JavaScript.

If we were to refer to our form field above as Document.Forms[0].UserId, for example, we'd get an error. JavaScript expects us to refer to both the "document" and "forms" elements as all lowercase. You can't use uppercase, not even for the first character.

Similarly, since we named the form field UserId, we must refer to it exactly that way. If we referred to it as document.forms[0].userid, or even document.forms[0].Userid, we'd receive an error either way.

Forcing the Focus()
In order to set the focus, we use the focus method, which is specified with parentheses after it, like a function in CF - though JavaScript methods are specified by appending them to the end of the name of the object they'll work on. To set the focus for our form field called "UserId", we might specify it as:


That's about it. There's nothing to be specified within the parentheses. (Notice that the word focus is also all lowercase.) This statement, when executed, will cause the named field in the named form to receive the focus when the page is displayed to the user.

Our final challenge is to decide where and how to specify this statement. Of course, it's JavaScript and must be specified to be executed as such. We mentioned earlier that this could be done by way of the <SCRIPT> tag. The following code will cause the focus to be placed on our UserId field:

<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">

If only it were this easy. Well, it is - almost! You just need to make sure the statement is executed after the form has been loaded. In JavaScript, as in ColdFusion, it's inappropriate to refer to a variable (or form field, as it were) before it's been defined. In this case, with this approach to executing the statement, we just need to be sure not to put this code on our page prior to the form itself.

There are multiple ways to specify JavaScript within a page. Besides the <SCRIPT> tag, we can also use event-handler attributes of other tags. For instance, we could also execute the JavaScript only after the entire page has loaded. Some may know that there's an attribute for the BODY tag called ONLOAD; it does just what we need, causing whatever statements it executes to be run only after the page has loaded. And since the form is within the page, we have another solution to our problem.

Fortunately, we can very easily specify our JavaScript statement (the statement itself, not the <SCRIPT> tags) by placing it in the BODY tag's ONLOAD attribute, as in:

<BODY ONLOAD="javascript:document.forms[0].UserId.focus()">

Pretty nifty! (The "javascript:" directive preceding the statement is not usually required, but it's the formal method of specifying JavaScript within the ONLOAD attribute.)

Experienced JavaScript developers may prefer yet another approach: creating a function instead and calling that function in the ONLOAD.

But Will It Fail?
You should have no trouble if you specify the JavaScript statement using one of the two appropriate approaches, refer to the form field using the naming references indicated, remember to specify the proper case for the naming reference and ensure that the statement occurs only after the form has been loaded.

There are a couple of other edge cases to be aware of, however. First, some folks use a single page to serve as both the form and action page (loaded from within the same CF template, for instance). That's fine, and can be a powerful way to reuse lots of code, but be careful: if you leave JavaScript code referring to the form field on the page, you'll get an error when it's acting as the form's action page - because the form itself won't usually have been sent on that page. This is particularly risky when using the ONLOAD approach, because you may not think of it when coding the page to serve both the form and action page.

In a similar vein, you don't want to include the JavaScript statement on the page if the form field to which it's referring isn't included in the page. With a tool like ColdFusion dynamically building the page, this isn't so strange as it might sound. Forewarned is forearmed.

What if a user's browser simply doesn't support JavaScript? With the <SCRIPT> tag approach described above, you may notice that just inside the opening and closing <SCRIPT> tags there are HTML comment tags. This is a standard JavaScript approach that guarantees that if the browser doesn't support the <SCRIPT> tag (which it will simply ignore), it will also ignore the JavaScript statements inside the script and comment tags. But browsers that support JavaScript still do execute the statements inside the comment tags. As musician Bruce Hornsby sang, "That's just the way it is."

With the ONLOAD approach, browsers that ignore JavaScript will also ignore attributes they don't understand. The ONLOAD attribute is purely and simply for executing JavaScript and hence is ignored by non-JS browsers. By association, the value specified for that attribute (our JavaScript statement in the second method above) is also ignored.

Some Caveats
Why not add the focus method to the first input field to the forms in all your pages? Well, first it may not be appropriate to the interface. On some pages, the form and its input fields may not really be the focus of the page. Let's take a look for example at the front page of the Allaire Developer's Exchange, at www.allaire.com/developer/gallery.cfm (see Figure 1).

If you look closely, there is indeed a form on this page but it's definitely not the focus of the page - it appears in the lower-right corner of the screen. Were we to put the focus there by default, it would be fine for someone about to enter his or her e-mail address; the signup form, however, clearly isn't the focus of this page, so giving it the focus would be inappropriate.

There are other forms at the Allaire site, such as the Knowledge Base search form www.allaire.com/Support/KnowledgeBase/SearchForm.cfm, which have as their sole purpose the entry of search criteria for their respective pages. So putting the focus on the input field there would indeed be appropriate.

Another issue is that the e-mail signup form is also located quite far down the page, so even if we did choose to give it the focus, an unintended result would be that the screen would scroll down when displayed to the user so that the focus (that form input field) was visible. This may cause the top of the page to be hidden from the user. Remember too that users often have different (and lower resolution) monitors than developers, increasing the chances of this problem developing. It can also happen if the users don't maximize their screen when displaying your page.

Afterword: Using SCRIPTJ in Studio
One last comment. This article has been as much an introduction to using JavaScript as it has been about the specifics of setting the form field focus. As such, there's one last really useful trick you should know about. It's a feature of ColdFusion Studio and its sister product HomeSite.

Remembering again the <SCRIPT> tags offered above, with the HTML comment characters specified within them, I mentioned that these are a standard set of tags to be used for all JavaScript entered within a page (other than that entered within other tag attributes like ONLOAD).

Well, you could hope to remember to enter that properly formatted set of basic tags...

<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">

...or you could take advantage of a really nifty shortcut in Studio: simply type SCRIPTJ, press CTRL-J (the control key and J) and watch as Studio converts that into the set of tags offered above. The cursor is even sitting within the paired tags waiting for you to type in your JavaScript. (Hey, now there's a great use of cursor focus!)

Using the focus method is a win-win that should be used in nearly all Web pages. Plus it really is just a single statement of JavaScript code in nearly all cases. So now do you see why I find it so frustrating when a site doesn't use it?

More Stories By Charlie Arehart

A veteran ColdFusion developer since 1997, Charlie Arehart is a long-time contributor to the community and a recognized Adobe Community Expert. He's a certified Advanced CF Developer and Instructor for CF 4/5/6/7 and served as tech editor of CFDJ until 2003. Now an independent contractor (carehart.org) living in Alpharetta, GA, Charlie provides high-level troubleshooting/tuning assistance and training/mentoring for CF teams. He helps run the Online ColdFusion Meetup (coldfusionmeetup.com, an online CF user group), is a contributor to the CF8 WACK books by Ben Forta, and is frequently invited to speak at developer conferences and user groups worldwide.

Comments (2) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

Most Recent Comments
Cecilia Elman 11/17/08 11:12:08 AM EST

This article helped me focus on the field I wanted which was a user requirement. I noticed that it was written in 2000. This proves that good writing never goes out of style.

I would also like the user to go to the next field automatically after completing the field without pressing TAB or another key. I have my field validation set so all fields must be completed or they get an error. Yet I'm not getting ONCHANGE to work.

Thank you.

Michael White 11/03/07 09:11:25 AM EDT

now that ColdFusion 8 is out with it's dynamically loaded cfdiv layout areas and the cfmenu tag, how would you set the focus on a form loaded using ColdFusion.navigate() into a cfdiv?

@ThingsExpo Stories
DevOps at Cloud Expo – being held October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real r...
SYS-CON Events announced today that Systena America will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Systena Group has been in business for various software development and verification in Japan, US, ASEAN, and China by utilizing the knowledge we gained from all types of device development for various industries including smartphones (Android/iOS), wireless communication, security technology and IoT serv...
SYS-CON Events announced today that Cloud Academy will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud computing technologies. Ge...
SYS-CON Events announced today that Fusion, a leading provider of cloud services, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Fusion, a leading provider of integrated cloud solutions to small, medium and large businesses, is the industry’s single source for the cloud. Fusion’s advanced, proprietary cloud service platform enables the integration of leading edge solutions in the cloud, including cloud...
Five years ago development was seen as a dead-end career, now it’s anything but – with an explosion in mobile and IoT initiatives increasing the demand for skilled engineers. But apart from having a ready supply of great coders, what constitutes true ‘DevOps Royalty’? It’ll be the ability to craft resilient architectures, supportability, security everywhere across the software lifecycle. In his keynote at @DevOpsSummit at 20th Cloud Expo, Jeffrey Scheaffer, GM and SVP, Continuous Delivery Busine...
SYS-CON Events announced today that Interoute has been named “Bronze Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Interoute is the owner operator of Europe's largest network and a global cloud services platform, which encompasses over 70,000 km of lit fiber, 15 data centers, 17 virtual data centers and 33 colocation centers, with connections to 195 additional partner data centers. Our full-service Unifie...
SYS-CON Events announced today that Ocean9will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Ocean9 provides cloud services for Backup, Disaster Recovery (DRaaS) and instant Innovation, and redefines enterprise infrastructure with its cloud native subscription offerings for mission critical SAP workloads.
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with the 21st International Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. @ThingsExpo Silicon Valley Call for Papers is now open.
SYS-CON Events announced today that Enzu will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY, and the 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enzu’s mission is to be the leading provider of enterprise cloud solutions worldwide. Enzu enables online businesses to use its IT infrastructure to their competitive ad...
Everywhere we turn in our industry we can find strong opinions about the direction, type and nature of cloud’s impact on computing and business. Another word that is used in every context in our industry is “hybrid.” In his session at 20th Cloud Expo, Alvaro Gonzalez, Director of Technical, Partner and Field Marketing at Peak 10, will use a combination of a few conceptual props and some research recently commissioned by Peak 10 to offer a real-world consideration of how the various categories of...
SYS-CON Events announced today that CollabNet, a global leader in enterprise software development, release automation and DevOps solutions, will be a Bronze Sponsor of SYS-CON's 20th International Cloud Expo®, taking place from June 6-8, 2017, at the Javits Center in New York City, NY. CollabNet offers a broad range of solutions with the mission of helping modern organizations deliver quality software at speed. The company’s latest innovation, the DevOps Lifecycle Manager (DLM), supports Value S...
SYS-CON Events announced today that SoftLayer, an IBM Company, has been named “Gold Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. SoftLayer, an IBM Company, provides cloud infrastructure as a service from a growing number of data centers and network points of presence around the world. SoftLayer’s customers range from Web startups to global enterprises.
SYS-CON Events announced today that Peak 10, Inc., a national IT infrastructure and cloud services provider, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Peak 10 provides reliable, tailored data center and network services, cloud and managed services. Its solutions are designed to scale and adapt to customers’ changing business needs, enabling them to lower costs, improve performance and focus intern...
Multiple data types are pouring into IoT deployments. Data is coming in small packages as well as enormous files and data streams of many sizes. Widespread use of mobile devices adds to the total. In this power panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists will look at the tools and environments that are being put to use in IoT deployments, as well as the team skills a modern enterprise IT shop needs to keep things running, get a handle on all this data, and deli...
SYS-CON Events announced today that Linux Academy, the foremost online Linux and cloud training platform and community, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Linux Academy was founded on the belief that providing high-quality, in-depth training should be available at an affordable price. Industry leaders in quality training, provided services, and student certification passes, its goal is to c...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend @CloudExpo | @ThingsExpo, June 6-8, 2017, at the Javits Center in New York City, NY and October 31 - November 2, 2017, Santa Clara Convention Center, CA. Learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
SYS-CON Events announced today that Loom Systems will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Founded in 2015, Loom Systems delivers an advanced AI solution to predict and prevent problems in the digital business. Loom stands alone in the industry as an AI analysis platform requiring no prior math knowledge from operators, leveraging the existing staff to succeed in the digital era. With offices in S...
SYS-CON Events announced today that EARP Integration will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. EARP Integration is a passionate software house. Since its inception in 2009 the company successfully delivers smart solutions for cities and factories that start their digital transformation. EARP provides bespoke solutions like, for example, advanced enterprise portals, business intelligence systems an...
We build IoT infrastructure products - when you have to integrate different devices, different systems and cloud you have to build an application to do that but we eliminate the need to build an application. Our products can integrate any device, any system, any cloud regardless of protocol," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA
SYS-CON Events announced today that Hitachi Data Systems, a wholly owned subsidiary of Hitachi LTD., will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City. Hitachi Data Systems (HDS) will be featuring the Hitachi Content Platform (HCP) portfolio. This is the industry’s only offering that allows organizations to bring together object storage, file sync and share, cloud storage gateways, and sophisticated search and...