Home > Articles

JavaScript in Action

  • Print
  • + Share This
Not only are JavaScript inputs and outputs great for being able to write JavaScript code that will communicate two-way with the user, but exploring this area of JavaScript is also a great place to begin your journey to proficiency! In this excerpt from JavaScript 1.5 by Example, authors Adrian and Kathie Kingsley-Hughes take a look at JavaScript objects-c their methods and properties-and how to use inputs and outputs.
This article is derived from JavaScript 1.5 by Example .
This chapter is from the book

This chapter is from the book

Exploring JavaScript Inputs and Outputs

Not only are JavaScript inputs and outputs great for being able to write JavaScript code that will communicate two-way with the user, but exploring this area of JavaScript is also a great place to begin your journey to proficiency!

Computing is all about inputs and outputs. Data goes in and data comes out. Without inputs and outputs, nothing would happen and nothing would get done. A word processor doesn't begin to do anything until it receives input from the user (usually in the form of characters generated by keystrokes), and this then leads to an output (it is outputted onto the screen and subsequently to paper or electronically).

Here, we are going to use JavaScript to control inputs and outputs in the form of various types of message boxes (guaranteed, if you've been surfing the Web for more than a few minutes, you've seen these message boxes before!).

Three types of message boxes can be conjured up using JavaScript:

  • Alert—This is for outputting information.

  • Confirm—This outputs information and allows the user to input a choice in the form of a yes/no question.

  • Prompt—This outputs some information and enables the user to type in a response to the output.

NOTE

Why do the message boxes in Internet Explorer look so different from the message boxes in Netscape Navigator? This actually has nothing to do with JavaScript—they are different because the alert, confirm, and prompt windows are generated by the browser. These boxes are only triggered by JavaScript. Because of this, each browser adds its own uniqueness to the look.

alert(), confirm(), and prompt() are actually all methods of the browser's Window object.

Objects, Methods and Properties

One thing you've probably heard about JavaScript is that it is an object-oriented language. But what does this really mean? To understand this, you need to be familiar with three terms:

  • Objects

  • Methods

  • Properties

What follows is a brief look at the three. After you have used JavaScript for a little while, you'll find yourself using them a lot more, so we can leave the detailing of them until later.

Objects

Put simply, an object is a thing, anything. Just as things in the real world are objects (cars, dogs, dollar bills, and so on), things in the computer world are regarded as objects, too.

To JavaScript, its objects all live in the Web browser. These are things like the browser window itself, forms, and parts of forms such as buttons and text boxes. JavaScript also has its own group of intrinsic, or built-in, objects as well, which relate to things such as arrays, dates, and so on. At the moment, you don't need to think too much about these objects because they'll be covered later; for now you just need to get some of the necessary terminology in place.

But it is objects that make JavaScript object-oriented. JavaScript is organized around objects rather than actions; to put it another way, it's organized around data rather than the logic of the programming. Object-oriented programming takes the viewpoint that what you really care about are the objects you want manipulated and not the logic required to manipulate them. One of the benefits of this is that—because you are freed from the logic of the programming—not only is the process of programming (or scripting) easier, but there are also many ways to perform a particular operation.

Methods

Methods are things that objects can do. In the real world, objects have methods. Cars move, dogs bark, dollars buy, and so on. alert() is a method of the Window object, so the Window object can alert the user with a message box. Examples of other methods are that windows can be opened or closed and buttons clicked. The three methods here are open(), close(), and click().

Note the parentheses. Look out for these because they signal that methods are being used, as opposed to properties.

Properties

All objects have properties. Cars have wheels and dogs have fur. For JavaScript, things such as the browser have a name and version number.

TIP

It might help you to think of objects and properties as things and methods as actions.

Using the alert() Method

alert() is the easiest of the three methods to use. You can use it to display textual information to the user in a simple, concise way. When the user is finished reading the message, she simply must click OK to get rid of it.

First, open your template HTML page in your favorite text editor and save it with a new name in a convenient location on your hard drive:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--Cloaking device on!
//Cloaking device off -->
</script>
</head>
<body>
</body>
</html>

NOTE

Remember to save it with the file extension HTM or HTML; otherwise, things won't work as planned.

CAUTION

Remember that JavaScript is a case-sensitive language.

To conjure the alert message box, type in the following:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--Cloaking device on!
alert();
//Cloaking device off -->
</script>
</head>
<body>
</body>
</html>

NOTE

The semicolon at the end of the alert()method is called a line terminator and is required to make your JavaScript ECMA-compliant (although it will work properly without it).

Now, for the message that you want displayed. This is placed inside quote marks inside the parentheses:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--Cloaking device on!
alert("An alert triggered by JavaScript!");
//Cloaking device off -->
</script>
</head>
<body>
</body>
</html>

Save the page, load it into the browser, and watch the message appear.

Making a second alert appear is just as simple as making the first one appear—just add alert() to the <script> block underneath the first and add your own message surrounded by quotes:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript ">
<!--Cloaking device on!
alert("An alert triggered by JavaScript!");
alert("A second message appears!");
//Cloaking device off -->
</script>
</head>
<body>
</body>
</html>

Save the file in the text editor and refresh the browser. This time notice that two messages come up. But more importantly, notice how they are displayed separately, instead of one on top of the other. What this shows is that the JavaScript stopped between each and didn't just blindly run to the end of the script. It waited patiently until the user clicked OK on the first box before going on to display the second.

TIP

Remember to resave the file before viewing the changes you've made. You wouldn't believe the number of users who forget this step and think they have done something wrong!

Adding Comments to JavaScript

Professional JavaScripters strive to make it easy to reread their code when they come back to it (maybe many months later). One of the things they use to help them is the JavaScript comment tags, one of which you've already come across in the previous chapter—the single-line comment.

Single-Line Comments

Here is an example of single-line comment tags in action:

<head>
<title>A Simple Page</title>
<script language="JavaScript ">
<!--Cloaking device on!
//The first alert is below
alert("An alert triggered by JavaScript!");
//Here is the second alert
alert("A second message appears!");
//Cloaking device off -->
</script>
</head>
<body>
</body>
</html>

If you run this JavaScript, you won't notice any difference at all. That is because the comment tags have done their job and hidden the comments from the browser's view.

Multi-Line Comments

Sometimes you need to add multiple-line comments to your scripts, and although you could go round placing slashes (/) at the beginning of each line, it isn't really convenient. This is where the multi-line comment tags come into their own.

Multi-line comment tags consist of the open comment tag (*) and then the comments themselves followed by the closing comment tag (/).

Here is an example of a multi-line comment:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript ">
<!--Cloaking device on!
/*
Below two alert()methods are used to
fire up two message boxes -note how the
second one fires after the OK button on the
first has been clicked
*/
alert("An alert triggered by JavaScript!");
alert("A second message appears!");
//Cloaking device off -->
</script>
</head>
<body>
</body>
</html>

Adding meaningful comments to a script is something that only comes with practice. At first, it might seem tedious or even unnecessary, but not only does it make your JavaScripts easier to understand, in the early stages it helps you get a clearer idea of how your scripts work. Take every opportunity possible to comment your scripts!

Using the confirm() Method

The confirm() method works similarly to alert(), but this box is used to give the user a choice between OK and Cancel. You can make it appear in pretty much the same way, with the only difference being that instead of using the alert() method, you use the confirm() method.

So again, following the same routine as for the alert() method, you begin by adding the confirm()method to the script block as follows:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript ">
<!--Cloaking device on!
confirm();
//Cloaking device off -->
</script>
</head>
<body>
</body>
</html>

And again, the message you want to appear in the box is typed inside the parentheses, contained in quotes:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript ">
<!--Cloaking device on!
confirm("Which one will you choose?");
//Cloaking device off -->
</script>
</head>
<body>
</body>
</html>

Save the file (again under a different name from the template and remembering to use the HTM or HTML file extension) and load it into the browser.

Now notice the buttons on the box: OK and Cancel. However, at the moment nothing happens when you click them except that the box disappears and the JavaScript continues to run again. Before you can use the buttons on the confirm box, you will need a few more JavaScript skills, after which you will revisit the confirm() method.

Using the prompt() Method

The prompt() method is a little different from the other two you have looked at in the course of this chapter. This is the only one that either allows the user to type in his own response to the question, instead of the script just processing information it already has (as with the alert() method), or allows the user to choose OK or Cancel (available using the confirm() method).

You add the prompt() method in much the same way as the other two. To begin with, add the prompt() method to the <script> block:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript ">
<!--Cloaking device on!
prompt();
//Cloaking device off -->
</script>
</head>
<body>
</body>
</html>

The prompt() method now starts to differ from the other two methods because two pieces of text must be added within the parentheses. The first is the message you want to appear.

This is done in exactly the same way as before. Again, the text goes inside the parentheses and inside quotes:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript ">
<!--Cloaking device on!
prompt("What is your name?");
//Cloaking device off -->
</script>
</head>
<body>
</body>
</html>

If you save this page and view it in the browser, notice that the prompt appears, asking the user for his name.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020