Click here to close now.

Welcome!

Java Authors: Yeshim Deniz, Elizabeth White, Liz McMillan, Carmen Gonzalez, Navrup Johal

Related Topics: Java

Java: Article

Getting Focus()ed and a Quick JavaScript Lesson

Getting Focus()ed and a Quick JavaScript Lesson

Many new J2EE developers get caught up in focusing on the details and nuances of servlets and JSPs and, as a result, may not learn how to leverage JavaScript. Some may even dismiss it as too much hassle, given cross-browser compatibility issues.

For both audiences there's still value in learning at least a minimal amount about client-side scripting. Even learning about just one feature - setting the cursor on the first form field you may have - can bring measurable benefit to your site visitors.

In this month's Journeyman J2EE, we depart from pure J2EE topics to address this subject, which should be understood by any Web application developer. If you're a newcomer to JavaScript, I'll provide more than enough to get started.

Where's Your Focus?
Here's the motivation for the problem I want to solve: 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? Now, how do you get to the point of entering data into that first field?

Do you use your mouse to move the cursor to that first data entry area? Or are you a keyboard maven, like me, in which case you prefer to tab to such a field? The problem is you may have to hit the tab key several times before you can enter data.

Indeed, it's typical to visit sites with navigational toolbars across the top and/or left side of the form, forcing you 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.

If you think that's being pedantic, consider a simpler example. If you show users a page that clearly is expecting them to enter some data (perhaps a user ID or a search argument, etc.) before proceeding, why not put the cursor right on the data entry field rather than forcing them to use the mouse or keyboard to get there. It's a usability issue.

There's an incredibly simple solution. Just the tiniest bit of JavaScript is needed, a single line of code, really. This article shows how to use it and also lays the most basic foundation for using JavaScript, if you're new to it.

Laying the Foundation
The technique we're talking about 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 on nearly all Web browsers. (Microsoft calls its version of the language 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 shows you the simplest application of this focus method. It's pretty straightforward and should work fine in most instances. JavaScript is widely supported by most browsers now, and this particular feature is supported 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.

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, there are several ways to do this. 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 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 almost 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 to specify JavaScript code to indicate that we want to place the focus on a particular field. We're almost there.

Focus on Forms
The focus() method operates on form fields. One of the many powers of JavaScript is that not only can we refer to (display, test) all the elements of our page (all the forms, form fields, indeed every tag and its contents and attributes), 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 know that you can give a name to a form field, and in JSP/servlets that will become the name of an attribute in the request scope on the form's action page. In our JavaScript we can use that same name to refer to the form field to give it focus. 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 other form field information would be provided both before and after this input field. However, it's important to know that this does indeed (and must) occur within a <FORM> tag.

One reason it'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. On a simple level we might 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. Indeed, there are rules that describe how to refer to elements on a page within JavaScript. It's called the Document Object Model (DOM). In any case, we need 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 by name or by indicating the relative location of the form on the page. Which is appropriate for you depends on your situation. If you've specified a NAME attribute on the <FORM> tag, you'd use that name.

If we had specified NAME="Login" on the <FORM> tag, 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 might not seem necessary, the contents of the page are considered to be within the "document" on the page (again, recall the "Document" Object Model). 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's 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 Java) 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 first or 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 if it's not specified correctly, you'll receive an error.

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

If we were to refer to our form field 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.

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()
To set the focus we use the focus method just like a reference to an object's method in Java. 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. In other words, the cursor will be resting on that field when the page is loaded.

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 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 need to be sure not to put this code on our page prior to the form itself.

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

Fortunately, we can 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 an attribute like ONLOAD.)

Experienced 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:

  1. Specify the JavaScript statement using one of the two appropriate approaches.
  2. Refer to the form field using the naming references indicated.
  3. Remember to specify the proper case for the naming reference.
  4. 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 JSP 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, but the output of the action page (POST) processing doesn't show the form (because you're showing the results of processing the form, not the form), you'll get an error. This is particularly risky when using the ONLOAD approach, because you may not think of it as serving both the form and action page when coding the page.

In a similar vein, and equally tricky in some situations, 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 dynamically built pages as in JSP and servlets, this isn't as strange as it might seem. Forewarned is forearmed.

What if a user's browser simply doesn't support JavaScript? There's very good news.

With the <SCRIPT> tag approach described earlier, you may notice that just inside the opening and closing <SCRIPT> tags 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. However, browsers that support JavaScript still execute the statements inside the comment tags.

With the ONLOAD approach as well, browsers that ignore JavaScript also won't recognize JavaScript-related attributes. 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 approach) is also ignored.

Some Caveats
Should you go ahead and add the focus method for the first input field of 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. Consider a page that happens to have a search field on it, such as http://industry.java.sun.com/solutions/ (see Figure 1).

If you look closely at the top right corner, there is indeed a "form" on this page for searching the site, but it's definitely not the focus of the page. There's also a search field to "Find a Solution" on the right-hand side. Should we put the focus in the first form field? The second? Either? Maybe neither. If you put it on the second, which may seem a focus of the page, keyboard users would find that tabbing once wouldn't take them to the top nav bar but instead to the links under that search field. That's not good usability, either.

Another reason not to blindly set the focus on any first form on the page is if the form doesn't appear at the top of the page. If we did that, an unintended result would be that the screen would be scrolled down when displayed, so that the field with 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.

When would it be appropriate to put the focus on a field? When the form is clearly the focus of the page. Going back to the previous example at Sun's Solutions Marketplace, consider the link under that "Find a Solution" button, labeled "Enroll Your Company." On the page that will be shown, it prompts for Company Name. That's clearly the focus of the page, so putting the focus on that field would make sense (sadly, they're not setting the focus using this approach as of this writing).

If you visit www.altavista.com, a popular search engine, you'll see that searching is clearly the focus of the page, and they do indeed use the focus method so that you can start typing search criteria as soon as the page appears.

Another natural example, and one that nearly all developers end up dealing with, is a login page that's presented to enter a site or access secured areas. If the user can't proceed without entering a user ID/password and the prompt for this is the only reason the page is being presented, there's little reason not to set the focus on the UserId field.

Afterword: Using SCRIPTJ in JRun Studio
There's one last useful trick that will be of interest to users of JRun Studio (a similar feature may exist in other IDEs). It also works in its sister Macromedia products, ColdFusion Studio and HomeSite.

Remember <SCRIPT> tags offered earlier 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).

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 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 there 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 many Web forms. JavaScript is ignored in browsers that don't support it or have it turned off, and being a JavaScript 1.0 element it works even in Netscape 2 and IE 3. Plus, it really is just a single statement of JavaScript code in nearly all cases. Now do you see why I find it so frustrating when a site doesn't use it? I hope newcomers to JavaScript have also learned a few things.

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
Fernando 01/09/02 06:25:00 PM EST

It is surprising sometimes how we forget about trying to releave the work load to servers. For example for form validation it becomes useful as it releases stress put on the server..Let the client check for its own mess before the server does :)

Satish 01/09/02 12:46:00 AM EST

This article by Charles Arehart on Java Script made me to refresh the most basic and useful concepts.

thanks a lot, regards
Satihs

@ThingsExpo Stories
WebRTC is an up-and-coming standard that enables real-time voice and video to be directly embedded into browsers making the browser a primary user interface for communications and collaboration. WebRTC runs in a number of browsers today and is currently supported in over a billion installed browsers globally, across a range of platform OS and devices. Today, organizations that choose to deploy WebRTC applications and use a host machine that supports audio through USB or Bluetooth can use Plantronics products to connect and transit or receive the audio associated with the WebRTC session.
The best mobile applications are augmented by dedicated servers, the Internet and Cloud services. Mobile developers should focus on one thing: writing the next socially disruptive viral app. Thanks to the cloud, they can focus on the overall solution, not the underlying plumbing. From iOS to Android and Windows, developers can leverage cloud services to create a common cross-platform backend to persist user settings, app data, broadcast notifications, run jobs, etc. This session provides a high level technical overview of many cloud services available to mobile app developers, includi...
SYS-CON Media announced today that @WebRTCSummit Blog, the largest WebRTC resource in the world, has been launched. @WebRTCSummit Blog offers top articles, news stories, and blog posts from the world's well-known experts and guarantees better exposure for its authors than any other publication. @WebRTCSummit Blog can be bookmarked ▸ Here @WebRTCSummit conference site can be bookmarked ▸ Here
There are lots of challenges in IoT around secure, scalable and business friendly infrastructure for enterprises. For large corporations, IoT implementations are one of the top priorities of the decade. All industries are seeing a competitive need to sustain by investing in IoT initiatives. The value addition comes from improved customer service, innovative product and additional revenue streams. The data from these IP-connected devices can be leveraged for a variety of business applications as well as responsive action controls. The various architectural building blocks of an IoT ...
SYS-CON Events announced today that Ciqada will exhibit at SYS-CON's @ThingsExpo, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Ciqada™ makes it easy to connect your products to the Internet. By integrating key components - hardware, servers, dashboards, and mobile apps - into an easy-to-use, configurable system, your products can quickly and securely join the internet of things. With remote monitoring, control, and alert messaging capability, you will meet your customers' needs of tomorrow - today! Ciqada. Let your products take flight. For more inform...
Health care systems across the globe are under enormous strain, as facilities reach capacity and costs continue to rise. M2M and the Internet of Things have the potential to transform the industry through connected health solutions that can make care more efficient while reducing costs. In fact, Vodafone's annual M2M Barometer Report forecasts M2M applications rising to 57 percent in health care and life sciences by 2016. Lively is one of Vodafone's health care partners, whose solutions enable older adults to live independent lives while staying connected to loved ones. M2M will continue to gr...
Chuck Piluso will present a study of cloud adoption trends and the power and flexibility of IBM Power and Pureflex cloud solutions. Speaker Bio: Prior to Data Storage Corporation (DSC), Mr. Piluso founded North American Telecommunication Corporation, a facilities-based Competitive Local Exchange Carrier licensed by the Public Service Commission in 10 states, serving as the company's chairman and president from 1997 to 2000. Between 1990 and 1997, Mr. Piluso served as chairman & founder of International Telecommunications Corporation, a facilities-based international carrier licensed by t...
Dave will share his insights on how Internet of Things for Enterprises are transforming and making more productive and efficient operations and maintenance (O&M) procedures in the cleantech industry and beyond. Speaker Bio: Dave Landa is chief operating officer of Cybozu Corp (kintone US). Based in the San Francisco Bay Area, Dave has been on the forefront of the Cloud revolution driving strategic business development on the executive teams of multiple leading Software as a Services (SaaS) application providers dating back to 2004. Cybozu's kintone.com is a leading global BYOA (Build Your O...
As enterprises move to all-IP networks and cloud-based applications, communications service providers (CSPs) – facing increased competition from over-the-top providers delivering content via the Internet and independently of CSPs – must be able to offer seamless cloud-based communication and collaboration solutions that can scale for small, midsize, and large enterprises, as well as public sector organizations, in order to keep and grow market share. The latest version of Oracle Communications Unified Communications Suite gives CSPs the capability to do just that. In addition, its integration ...
The IoT Bootcamp is coming to Cloud Expo | @ThingsExpo on June 9-10 at the Javits Center in New York. Instructor. Registration is now available at http://iotbootcamp.sys-con.com/ Instructor Janakiram MSV previously taught the famously successful Multi-Cloud Bootcamp at Cloud Expo | @ThingsExpo in November in Santa Clara. Now he is expanding the focus to Janakiram is the founder and CTO of Get Cloud Ready Consulting, a niche Cloud Migration and Cloud Operations firm that recently got acquired by Aditi Technologies. He is a Microsoft Regional Director for Hyderabad, India, and one of the f...
The 17th International Cloud Expo has announced that its Call for Papers is open. 17th International Cloud Expo, to be held November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, brings together Cloud Computing, APM, APIs, Microservices, Security, Big Data, Internet of Things, DevOps and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportunity. Submit your speaking proposal today!
While not quite mainstream yet, WebRTC is starting to gain ground with Carriers, Enterprises and Independent Software Vendors (ISV’s) alike. WebRTC makes it easy for developers to add audio and video communications into their applications by using Web browsers as their platform. But like any market, every customer engagement has unique requirements, as well as constraints. And of course, one size does not fit all. In her session at WebRTC Summit, Dr. Natasha Tamaskar, Vice President, Head of Cloud and Mobile Strategy at GENBAND, will explore what is needed to take a real time communications ...
SYS-CON Events announced today that Litmus Automation will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Litmus Automation’s vision is to provide a solution for companies that are in a rush to embrace the disruptive Internet of Things technology and leverage it for real business challenges. Litmus Automation simplifies the complexity of connected devices applications with Loop, a secure and scalable cloud platform.
In 2015, 4.9 billion connected "things" will be in use. By 2020, Gartner forecasts this amount to be 25 billion, a 410 percent increase in just five years. How will businesses handle this rapid growth of data? Hadoop will continue to improve its technology to meet business demands, by enabling businesses to access/analyze data in real time, when and where they need it. Cloudera's Chief Technologist, Eli Collins, will discuss how Big Data is keeping up with today's data demands and how in the future, data and analytics will be pervasive, embedded into every workflow, application and infra...
From telemedicine to smart cars, digital homes and industrial monitoring, the explosive growth of IoT has created exciting new business opportunities for real time calls and messaging. In his session at @ThingsExpo, Ivelin Ivanov, CEO and Co-Founder of Telestax, shared some of the new revenue sources that IoT created for Restcomm – the open source telephony platform from Telestax. Ivelin Ivanov is a technology entrepreneur who founded Mobicents, an Open Source VoIP Platform, to help create, deploy, and manage applications integrating voice, video and data. He is the co-founder of TeleStax, a...
As Marc Andreessen says software is eating the world. Everything is rapidly moving toward being software-defined – from our phones and cars through our washing machines to the datacenter. However, there are larger challenges when implementing software defined on a larger scale - when building software defined infrastructure. In his session at 16th Cloud Expo, Boyan Ivanov, CEO of StorPool, will provide some practical insights on what, how and why when implementing "software-defined" in the datacenter.
How is unified communications transforming the way businesses operate? In his session at WebRTC Summit, Arvind Rangarajan, Director of Product Marketing at BroadSoft, will discuss how to extend unified communications experience outside the enterprise through WebRTC. He will also review use cases across different industry verticals. Arvind Rangarajan is Director, Product Marketing at BroadSoft. He has over 19 years of experience in the telecommunications industry in various roles such as Software Development, Product Management and Product Marketing, applied across Wireless, Unified Communic...
SYS-CON Events announced today that MangoApps will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY., and the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. MangoApps provides private all-in-one social intranets allowing workers to securely collaborate from anywhere in the world and from any device. Social, mobile, and easy to use. MangoApps has been named a "Market Leader" by Ovum Research and a "Cool Vendor" by Gartner...
SYS-CON Media announced today that @ThingsExpo Blog launched with 7,788 original stories. @ThingsExpo Blog offers top articles, news stories, and blog posts from the world's well-known experts and guarantees better exposure for its authors than any other publication. @ThingsExpo Blog can be bookmarked. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago.
The world's leading Cloud event, Cloud Expo has launched Microservices Journal on the SYS-CON.com portal, featuring over 19,000 original articles, news stories, features, and blog entries. DevOps Journal is focused on this critical enterprise IT topic in the world of cloud computing. Microservices Journal offers top articles, news stories, and blog posts from the world's well-known experts and guarantees better exposure for its authors than any other publication. Follow new article posts on Twitter at @MicroservicesE