Welcome!

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');
</SCRIPT>

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">
-
</FORM>

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:

document.forms[0].UserId.

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:

document.forms[0].UserId.focus()

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">
<!--
document.forms[0].UserId.focus()
//-->
</SCRIPT>

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!)

Summary
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
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
As hybrid cloud becomes the de-facto standard mode of operation for most enterprises, new challenges arise on how to efficiently and economically share data across environments. In his session at 21st Cloud Expo, Dr. Allon Cohen, VP of Product at Elastifile, will explore new techniques and best practices that help enterprise IT benefit from the advantages of hybrid cloud environments by enabling data availability for both legacy enterprise and cloud-native mission critical applications. By rev...
Organizations do not need a Big Data strategy; they need a business strategy that incorporates Big Data. Most organizations lack a road map for using Big Data to optimize key business processes, deliver a differentiated customer experience, or uncover new business opportunities. They do not understand what’s possible with respect to integrating Big Data into the business model.
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, will discuss how they b...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
SYS-CON Events announced today that Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
SYS-CON Events announced today that TidalScale will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
Amazon is pursuing new markets and disrupting industries at an incredible pace. Almost every industry seems to be in its crosshairs. Companies and industries that once thought they were safe are now worried about being “Amazoned.”. The new watch word should be “Be afraid. Be very afraid.” In his session 21st Cloud Expo, Chris Kocher, a co-founder of Grey Heron, will address questions such as: What new areas is Amazon disrupting? How are they doing this? Where are they likely to go? What are th...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, will lead you through the exciting evolution of the cloud. He'll look at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering ...