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
Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the USA and Europe, we work with a variety of customers from emerging startups to Fortune 1000 companies.
The age of Digital Disruption is evolving into the next era – Digital Cohesion, an age in which applications securely self-assemble and deliver predictive services that continuously adapt to user behavior. Information from devices, sensors and applications around us will drive services seamlessly across mobile and fixed devices/infrastructure. This evolution is happening now in software defined services and secure networking. Four key drivers – Performance, Economics, Interoperability and Trust ...
Financial Technology has become a topic of intense interest throughout the cloud developer and enterprise IT communities. Accordingly, attendees at the upcoming 20th Cloud Expo at the Javits Center in New York, June 6-8, 2017, will find fresh new content in a new track called FinTech.
SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 20th Cloud Expo, which will take place on June 6-8, 2017 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 add...
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm.
Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more business becomes digital the more stakeholders are interested in this data including how it relates to business. Some of these people have never used a monitoring tool before. They have a question on their mind like “How is my application doing” but no id...
Bert Loomis was a visionary. This general session will highlight how Bert Loomis and people like him inspire us to build great things with small inventions. In their general session at 19th Cloud Expo, Harold Hannon, Architect at IBM Bluemix, and Michael O'Neill, Strategic Business Development at Nvidia, discussed the accelerating pace of AI development and how IBM Cloud and NVIDIA are partnering to bring AI capabilities to "every day," on-demand. They also reviewed two "free infrastructure" pr...
SYS-CON Events announced today that Juniper Networks (NYSE: JNPR), an industry leader in automated, scalable and secure networks, 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. Juniper Networks challenges the status quo with products, solutions and services that transform the economics of networking. The company co-innovates with customers and partners to deliver automated, scalable and secure network...
The age of Digital Disruption is evolving into the next era – Digital Cohesion, an age in which applications securely self-assemble and deliver predictive services that continuously adapt to user behavior. Information from devices, sensors and applications around us will drive services seamlessly across mobile and fixed devices/infrastructure. This evolution is happening now in software defined services and secure networking. Four key drivers – Performance, Economics, Interoperability and Trust ...
In his keynote at @ThingsExpo, Chris Matthieu, Director of IoT Engineering at Citrix and co-founder and CTO of Octoblu, focused on building an IoT platform and company. He provided a behind-the-scenes look at Octoblu’s platform, business, and pivots along the way (including the Citrix acquisition of Octoblu).
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 an...
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo 2016 in New York. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place June 6-8, 2017, at the Javits Center in New York City, New York, is co-located with 20th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry p...
@GonzalezCarmen has been ranked the Number One Influencer and @ThingsExpo has been named the Number One Brand in the “M2M 2016: Top 100 Influencers and Brands” by Analytic. Onalytica analyzed tweets over the last 6 months mentioning the keywords M2M OR “Machine to Machine.” They then identified the top 100 most influential brands and individuals leading the discussion on Twitter.
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound e...
@ThingsExpo has been named the Most Influential ‘Smart Cities - IIoT' Account and @BigDataExpo has been named fourteenth by Right Relevance (RR), which provides curated information and intelligence on approximately 50,000 topics. In addition, Right Relevance provides an Insights offering that combines the above Topics and Influencers information with real time conversations to provide actionable intelligence with visualizations to enable decision making. The Insights service is applicable to eve...
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 Grape Up 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. Grape Up is a software company specializing in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the U.S. and Europe, Grape Up works with a variety of customers from emergi...
SYS-CON Events announced today that T-Mobile 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. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on ...
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...
With billions of sensors deployed worldwide, the amount of machine-generated data will soon exceed what our networks can handle. But consumers and businesses will expect seamless experiences and real-time responsiveness. What does this mean for IoT devices and the infrastructure that supports them? More of the data will need to be handled at - or closer to - the devices themselves.