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
From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
SYS-CON Events announced today that Elastifile 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. Elastifile Cloud File System (ECFS) is software-defined data infrastructure designed for seamless and efficient management of dynamic workloads across heterogeneous environments. Elastifile provides the architecture needed to optimize your hybrid cloud environment, by facilitating efficient...
Recently, IoT seems emerging as a solution vehicle for data analytics on real-world scenarios from setting a room temperature setting to predicting a component failure of an aircraft. Compared with developing an application or deploying a cloud service, is an IoT solution unique? If so, how? How does a typical IoT solution architecture consist? And what are the essential components and how are they relevant to each other? How does the security play out? What are the best practices in formulating...
In his session at @ThingsExpo, Arvind Radhakrishnen discussed how IoT offers new business models in banking and financial services organizations with the capability to revolutionize products, payments, channels, business processes and asset management built on strong architectural foundation. The following topics were covered: How IoT stands to impact various business parameters including customer experience, cost and risk management within BFS organizations.
SYS-CON Events announced today that Golden Gate University 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. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, will introduce two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a...
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
21st International Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Me...
SYS-CON Events announced today that Secure Channels, a cybersecurity firm, 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. Secure Channels, Inc. offers several products and solutions to its many clients, helping them protect critical data from being compromised and access to computer networks from the unauthorized. The company develops comprehensive data encryption security strategie...
In his session at @ThingsExpo, Sudarshan Krishnamurthi, a Senior Manager, Business Strategy, at Cisco Systems, discussed how IT and operational technology (OT) work together, as opposed to being in separate siloes as once was traditional. Attendees learned how to fully leverage the power of IoT in their organization by bringing the two sides together and bridging the communication gap. He also looked at what good leadership must entail in order to accomplish this, and how IT managers can be the ...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
There is only one world-class Cloud event on earth, and that is Cloud Expo – which returns to Silicon Valley for the 21st Cloud Expo at the Santa Clara Convention Center, October 31 - November 2, 2017. Every Global 2000 enterprise in the world is now integrating cloud computing in some form into its IT development and operations. Midsize and small businesses are also migrating to the cloud in increasing numbers. Companies are each developing their unique mix of cloud technologies and service...
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
SYS-CON Events announced today that App2Cloud 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. App2Cloud is an online Platform, specializing in migrating legacy applications to any Cloud Providers (AWS, Azure, Google Cloud).
IoT is at the core or many Digital Transformation initiatives with the goal of re-inventing a company's business model. We all agree that collecting relevant IoT data will result in massive amounts of data needing to be stored. However, with the rapid development of IoT devices and ongoing business model transformation, we are not able to predict the volume and growth of IoT data. And with the lack of IoT history, traditional methods of IT and infrastructure planning based on the past do not app...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. Jack Norris reviews best practices to show how companies develop, deploy, and dynamically update these applications and how this data-first...
Intelligent Automation is now one of the key business imperatives for CIOs and CISOs impacting all areas of business today. In his session at 21st Cloud Expo, Brian Boeggeman, VP Alliances & Partnerships at Ayehu, will talk about how business value is created and delivered through intelligent automation to today’s enterprises. The open ecosystem platform approach toward Intelligent Automation that Ayehu delivers to the market is core to enabling the creation of the self-driving enterprise.
Internet-of-Things discussions can end up either going down the consumer gadget rabbit hole or focused on the sort of data logging that industrial manufacturers have been doing forever. However, in fact, companies today are already using IoT data both to optimize their operational technology and to improve the experience of customer interactions in novel ways. In his session at @ThingsExpo, Gordon Haff, Red Hat Technology Evangelist, shared examples from a wide range of industries – including en...