0% found this document useful (0 votes)
22 views25 pages

WT Unit 3 Notes

Uploaded by

mayur1000.m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views25 pages

WT Unit 3 Notes

Uploaded by

mayur1000.m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Unit 3

JavaScript

JavaScript: it is an object-oriented, dynamically typed, scripting language

Although it contains the word Java, JavaScript and Java are vastly different programming
languages with different uses. Java is a full-fledged compiled, objectoriented language, popular
for its ability to run on any platform with a Java Virtual Machine installed. Conversely,
JavaScript is one of the world’s most popular languages, with fewer of the object-oriented
features of Java, and runs directly inside the browser, without the need for the JVM.
JavaScript is dynamically typed (also called weakly typed) in that variables can be easily (or
implicitly) converted from one data type to another.

6.1.1 Client-Side Scripting


The idea of client-side scripting is an important one in web development. It refers to the client
machine (i.e., the browser) running code locally rather than relying on the server to execute code
and return the result. There are many client-side languages that have come into use over the past
decade including Flash, VBScript, Java, and JavaScript. Some of these technologies only work in
certain browsers, while others require plug-ins to function. We will focus on JavaScript due to its
browser interoperability (that is, its ability to work/operate on most browsers). Figure 6.1
illustrates how a client machine downloads and executes JavaScript code.
There are many advantages of client-side scripting:
■ Processing can be offloaded from the server to client machines, thereby reducing the load on
the server.
■ The browser can respond more rapidly to user events than a request to a remote server ever
could, which improves the user experience.
■ JavaScript can interact with the downloaded HTML in a way that the server cannot, creating a
user experience more like desktop software than simple HTML ever could.

The disadvantages of client-side scripting are mostly related to how programmers use JavaScript
in their applications. Some of these include:
■ There is no guarantee that the client has JavaScript enabled, meaning any required
functionality must be housed on the server, despite the possibility that it could be offloaded.
■ The idiosyncrasies between various browsers and operating systems make it difficult to test for
all potential client configurations. What works in one browser, may generate an error in another.
■ JavaScript-heavy web applications can be complicated to debug and maintain. JavaScript has
often been used through inline HTML hooks that are embedded into the HTML of a web page.
Although this technique has been used for years, it has the distinct disadvantage of blending
HTML and JavaScript together, which decreases code readability, and increases the difficulty of
web development.
3
6.1.2 JavaScript’s History and Uses
JavaScript was introduced by Netscape in their Navigator browser back in 1996. It originally was
called Live Script, but was renamed partly because one of its original purposes was to provide a
measure of control within the browser over Java applets.
JavaScript is in fact an implementation of a standardized scripting language called ECMAScript.
Internet Explorer (IE) at first did not support JavaScript, but instead had its own browser-based
scripting language (VBScript). While IE now does support JavaScript, Microsoft sometimes
refers to it as JScript, primarily for trademark reasons (Oracle currently owns the trademark for
JavaScript). It wasn’t until the middle of the 2000s with the emergence of so-called AJAX sites
that JavaScript became a much more important part of web development. AJAX is both an
acronym as well as a general term. As an acronym it means Asynchronous JavaScript and XML,
which was accurate for some time; but since XML is no longer always the data format for data
transport in AJAX sites, the acronym meaning is becoming less and less accurate. As a general
term, AJAX refers to a style of website development that makes use of JavaScript to create more
responsive user experiences. The most important way that this responsiveness is created is via
asynchronous data requests via JavaScript and the XML HttpRequest object. This addition to
JavaScript was introduced by Microsoft as an ActiveX control (the IE version of plug-ins) in
1999, but it wasn’t until sophisticated websites by Google (such as Gmail and Maps) and Flickr
demonstrated what was possible using these techniques that the term AJAX became popular.
The most important feature of AJAX sites is the asynchronous data requests. You will eventually
learn how to program these asynchronous data requests in Chapter 15. For now, however, we
should say a few words about how asynchronous requests are different from the normal HTTP
request-response loop. You might want to remind yourself about how the “normal” HTTP
request response loop looks. Figure 6.4 illustrates the processing flow for a page that requires
updates based on user input using the normal synchronous non-AJAX page request-response
loop.
As you can see in Figure 6.4, such interaction requires multiple requests to the server, which not
only slows the user experience, it puts the server under extra load, especially if, as the case in
Figure 6.4, each request is invoking a server-side script.

But as can be seen in Figure 6.5, when these multiple requests are being made across the Internet
to a busy server, then the time costs of the normal HTTP request response loop will be more
visually noticeable to the user. AJAX provides web authors with a way to avoid the visual and
temporal deficiencies of normal HTTP interactions. With AJAX web pages, it is possible to
update sections of a page by making special requests of the server in the background, creating
the illusion of continuity. Figure 6.6 illustrates how the interaction shown in Figure 6.4 would
differ in an AJAX-enhanced web page.
6.2 JavaScript Design Principles
As mentioned earlier, JavaScript does have a bad reputation for being a difficult language to use.
Although frameworks and developer tools can help, there is some truth to this reputation.
It should be said, however, that this reputation is based not so much on the language itself but in
how developers have tended to use it. JavaScript has often been used through inline HTML
hooks—that is, embedded into the HTML of a web page. Although this technique has been used
for years, it has the distinct disadvantage of blending HTML and JavaScript together, which
decreases code readability, and increases the difficulty of web development.

6.2.1 Layers
When designing software to solve a problem, it is often helpful to abstract the solution a little bit
to help build a cognitive model in your mind that you can then implement. Perhaps the most
common way of articulating such a cognitive model is via the term layer. In object-oriented
programming, a software layer is a way of conceptually grouping programming classes that have
similar functionality and dependencies. Common software design layer names include:
■ Presentation layer. Classes focused on the user interface.
■ Business layer. Classes that model real-world entities, such as customers, products, and sales.
■ Data layer. Classes that handle the interaction with the data sources.

Presentation Layer
This type of programming focuses on the display of information. JavaScript can alter the HTML
of a page, which results in a change, visible to the user. These presentation layer applications
include common things like creating, hiding, and showing divs, using tabs to show multiple
views, or having arrows to page through result sets. This layer is most closely related to the user
experience and the most visible to the end user.
Validation Layer
JavaScript can be also used to validate logical aspects of the user’s experience. This could
include, for example, validating a form to make sure the email entered is valid before sending it
along. It is often used in conjunction with the presentation layer to create a coherent user
experience, where a message to the presentation layer highlights bad fields. Both layers exist on
the client machine, although the intention is to prevalidate forms before making transmissions
back to the server.
Asynchronous Layers
Normally, JavaScript operates in a synchronous manner where a request sent to the server
requires a response before the next lines of code can be executed. During the wait between
request and response the browser sits in a loading state and only updates upon receiving the
response. In contrast, an asynchronous layer can route requests to the server in the background.
In this model, as certain events are triggered, the JavaScript sends the HTTP requests to the
server, but while waiting for the response, the rest of the application functions normally, and the
browser isn’t in a loading state. When the response arrives JavaScript will (perhaps) update a
portion of the page. Asynchronous layers are considered advanced versions of the presentation
and validation layers above.

6.3 Where Does JavaScript Go?


JavaScript can be linked to an HTML page in a number of ways. Just as CSS styles can be inline,
embedded, or external, JavaScript can be included in a number of ways. Just as with CSS these
can be combined, but external is the preferred method for cleanliness and ease of maintenance.
Running JavaScript scripts in your browser requires downloading the JavaScript code to the
browser and then running it. Pages with lots of scripts could potentially run slowly, resulting in a
degraded experience while users wait for the page to load. Different browsers manage the
downloading and loading of scripts in different ways, which are important things to realize when
you decide how to link your scripts.
6.3.1 Inline JavaScript
Inline JavaScript refers to the practice of including JavaScript code directly within certain
HTML attributes, such as that shown in Listing 6.1.

<a href="JavaScript:OpenWindow();"more info</a>


<input type="button” onclick="alert('Are you sure?');" />
listing 6.1 Inline JavaScript example

<script type="text/javascript">
/* A JavaScript Comment */
alert ("Hello World!");
</script>
listing 6.2 Embedded JavaScript example
You may recall that in Chapter 3 on CSS you were warned that inline CSS is in general a bad
practice and should be avoided. The same is true with JavaScript. In fact, inline JavaScript is
much worse than inline CSS. Inline JavaScript is a real maintenance nightmare, requiring
maintainers to scan through almost every line of HTML looking for your inline JavaScript.
6.3.2 Embedded JavaScript
Embedded JavaScript refers to the practice of placing JavaScript code within a <script> element
as shown in Listing 6.2. Like its equivalent in CSS, embedded JavaScript is okay for quick
testing and for learning scenarios, but is frowned upon for normal real world pages. Like with
inline JavaScript, embedded scripts can be difficult to maintain.

6.3.3 External JavaScript


Since writing code is a different competency than designing HTML and CSS, it is often
advantageous to separate the two into different files. JavaScript supports this separation by
allowing links to an external file that contains the JavaScript, as shown in Listing 6.3.
This is the recommended way of including JavaScript scripts in your HTML pages.
By convention, JavaScript external files have the extension .js. Modern websites often have links
to several, maybe even dozens, of external JavaScript files (also called libraries). These external
files typically contain function definitions, data definitions, and other blocks of JavaScript code.

<head>
<script type="text/JavaScript" src="greeting.js">
</script>
</head>
listing 6.3 External JavaScript example

6.4 Syntax
Since it’s a lightweight scripting language, JavaScript has some features (such as dynamic
typing) that are especially helpful to the novice programmer. However, a novice programmer
faces challenges when he or she tries to use JavaScript in the same way as a full object-oriented
language such as Java, as JavaScript’s object features (such as prototypes and inline functions)
are quite unlike those of more familiar languages.
We will briefly cover the fundamental syntax for the most common programming constructs
including variables, assignment, conditionals, loops, and arrays before moving on to advanced
topics such as events and classes.
JavaScript’s reputation for being quirky not only stems from its strange way of implementing
object-oriented principles, but also from some odd syntactic gotchas that every JavaScript
developer will eventually encounter, some of which include:
■ Everything is type sensitive, including function, class, and variable names.
■ The scope of variables in blocks is not supported. This means variables declared inside a loop
may be accessible outside of the loop, counter to what one would expect.
■ There is a === operator, which tests not only for equality but type equivalence.
■ Null and undefined are two distinctly different states for a variable.
■ Semicolons are not required, but are permitted (and encouraged).
■ There is no integer type, only number, which means floating-point rounding errors are
prevalent even with values intended to be integers.
var x;
var y = 0;
y = 4;
a variable x is defined
y is defined and initialized to 0
y is assigned the value of 4
Figure 6.13 Variable declaration and assignment

6.4.1 Variables
Variables in JavaScript are dynamically typed, meaning a variable can be an integer, and then
later a string, then later an object, if so desired. This simplifies variable declarations, so that we
do not require the familiar type fields like int, char, and String. Instead, to declare a variable x,
we use the var keyword, the name, and a semicolon as shown in Figure 6.13. If we specify no
value, then (being typeless) the default value is undefined. Assignment can happen at
declaration-time by appending the value to the declaration, or at run time with a simple right-to-
left assignment as illustrated in Figure 6.13. This syntax should be familiar to those who have
programmed in languages like C and Java. In addition, the conditional assignment operator,
shown in Figure 6.14, can also be used to assign based on condition, although its use is
sometimes discouraged.

6.4.2 Comparison Operators


The core of any programming language is the ability to distil things down to Boolean statements
where something is either true or false. JavaScript is no exception] and comes equipped with a
number of operators to compare two values, listed in Table 6.1.
/* x conditional assignment */
x = (y==4) ? "y is 4" : "y is not 4";
Condition Value
if true
Value
if false
Figure 6.14
The conditional assignment operator
6.4.3 Logical Operators
Comparison operators are useful, but without being able to combine several
together, their usefulness would be severely limited. Therefore, like most languages
JavaScript includes Boolean operators, which allow us to build complicated expressions.
The Boolean operators and, or, and not and their truth tables are listed in
Table 6.2. Syntactically they are represented with && (and), || (or), and ! (not).
6.4.4 Conditionals
JavaScript’s syntax is almost identical to that of PHP, Java, or C when it comes to
conditional structures such as if and if else statements. In this syntax the condition
to test is contained within ( ) brackets with the body contained in { } blocks.

Optional else if statements can follow, with an else ending the branch. Listing 6.4
uses a conditional to set a greeting variable, depending on the hour of the day.

var hourOfDay; // var to hold hour of day, set it later...


var greeting; // var to hold the greeting message.
if (hourOfDay > 4 && hourOfDay < 12){
// if statement with condition
greeting = "Good Morning";
}
else if (hourOfDay >= 12 && hourOfDay < 20){
// optional else if
greeting = "Good Afternoon";
}
else{ // optional else branch
greeting = "Good Evening";
}

6.4.5 Loops
Like conditionals, loops use the ( ) and { } blocks to define the condition and the
body of the loop.
While Loops
The most basic loop is the while loop, which loops until the condition is not met.
Loops normally initialize a loop control variable before the loop, use it in the condition,
and modify it within the loop. One must be sure that the variables that make
up the condition are updated inside the loop (or elsewhere) to avoid an infinite loop!
var i=0;
while(i < 10){
//do something with i
i++;
}
For Loops
A for loop combines the common components of a loop: initialization, condition,
and post-loop operation into one statement. This statement begins with the for
keyword and has the components placed between ( ) brackets, semicolon (;) separated
as shown in Figure 6.15.
for (var i = 0; i < 10; i++){
//do something with i
}
Figure 6.15 For loop

6.4.6 Functions
Functions are the building block for modular code in JavaScript, and are even used
to build pseudo-classes, which you will learn about later. They are defined by using
the reserved word function and then the function name and (optional) parameters.
Since JavaScript is dynamically typed, functions do not require a return type, nor do
the parameters require type. Therefore a function to raise x to the yth power might
be defined as:
function power(x,y){
var pow=1;
for (var i=0;i<y;i++){
pow = pow*x;
}
return pow;
}
And called as
power(2,10);
With new programmers there is often confusion between defining a function
and calling the function. Remember that when actually using the keyword function,
we are defining what the function does. Later, we can use or call that function by
using its given name without the function keyword.
Later in this chapter you will see the advanced use of functions to build classes.
Alert
The alert() function makes the browser show a pop-up to the user, with whatever
is passed being the message displayed. The following JavaScript code displays a
simple hello world message in a pop-up:
alert ( "Good Morning" );

6.5 JavaScript Objects


JavaScript is not a full-fledged object-oriented programming language. It does not have classes
per se, and it does not support many of the patterns you’d expect from an object-oriented
language like inheritance and polymorphism in a straightforward way.
The language does, however, support objects. User-defined objects are declared in a slightly odd
way to developers familiar with languages like C++ or Java, so the syntax to build pseudo-
classes can be challenging. Nonetheless the advantages of encapsulating data and methods into
objects outweigh the syntactic hurdle you will have to overcome.
Objects can have constructors, properties, and methods associated with them, and are used very
much like objects in other object-oriented languages. There are objects that are included in the
JavaScript language; you can also define your own kind of objects.
6.5.1 Constructors
Normally to create a new object we use the new keyword, the class name, and ( ) brackets with n
optional parameters inside, comma delimited as follows:
var someObject = new ObjectName(parameter 1,param 2,..., parameter n);
For some classes, shortcut constructors are defined, which can be confusing if we are not aware
of them. For example, a String object can be defined with the shortcut
var greeting = "Good Morning";
Instead of the formal definition
var greeting = new String("Good Morning");
Arrays are another class with a shortcut constructor, described later in this section.
2 6.6 The Document Object Model (DOM)
JavaScript is almost always used to interact with the HTML document in which it is contained.
As such, there needs to be some way of programmatically accessing the elements and attributes
within the HTML. This is accomplished through a programming interface (API) called the
Document Object Model
(DOM).
6.6.1 Nodes
In the DOM, each element within the HTML document is called a node. If the
DOM is a tree, then each node is an individual branch. There are element nodes, text nodes, and
attribute nodes, as shown in Figure 6.18.
All nodes in the DOM share a common set of properties and methods. Thus, most of the tasks
that we typically perform in JavaScript involve finding a node, and then accessing or modifying
it via those properties and methods. The most important of these are shown in Table 6.3.
6.6.2 Document Object
The DOM document object is the root JavaScript object representing the entire
HTML document. It contains some properties and methods that we will use extensively
in our development and is globally accessible as document.
The attributes of this object include some information about the page including
doctype and inputEncoding.
6.6.3 Element Node Object
The type of object returned by the method document.getElementById() described
in the previous section is an element node object. This represents an HTML element
in the hierarchy, contained between the opening <> and closing </> tags for this
element. As you may already have figured out, an element can itself contain more
elements.
Since IDs must be unique in an HTML document, getElementByID() returns a
single node, rather than a set of results which is the case with other selector functions.
The returned Element Node object has the node properties shown in Table 6.3. It also
has a variety of additional properties, the most important of which are shown in
Table 6.5.

6.6.4 Modifying a DOM Element


In many introductory JavaScript textbooks the document.write() method is used to
create output to the HTML page from JavaScript. While this is certainly valid, it always creates
JavaScript at the bottom of the existing HTML page, and in practice
is good for little more than debugging. The modern JavaScript programmer will want
to write to the HTML page, but in a particular location, not always at the bottom.
Using the DOM document and HTML DOM element objects, we can do
exactly that using the innerHTML property as shown in Listing 6.8 (using the HTML
shown in Figure 6.19).
Changing an Element’s Style
We can also modify the style associated with a particular block. We can add or
remove any style using the style or className property of the Element node,
which is something that you might want to do to dynamically change the appearance
of an element. Its usage is shown below to change a node’s background color
and add a three-pixel border.
var commentTag = document.getElementById("specificTag");
commentTag.style.backgroundColour = "#FFFF00";
commentTag.style.borderWidth="3px";

The className property is normally a better choice, because it allows the styles
to be created outside the code, and thus be better accessible to designers. Using this
model we would change the background color by having two styles defined, and
changing them in JavaScript code.
var commentTag = document.getElementById("specificTag");
commentTag.className = "someClassName";
HTML5 introduces the classList element, which allows you to add, remove,
or toggle a CSS class on an element. You could add a class with
label.classList.addClass("someClassName");

6.7 JavaScript Events


At the core of all JavaScript programming is the concept of an event. A JavaScript
event is an action that can be detected by JavaScript. Many of them are initiated by
user actions but some are generated by the browser itself. We say then that an event
is triggered and then it can be caught by JavaScript functions, which then do something
in response.
In the original JavaScript world, events could be specified right in the HTML
markup with hooks to the JavaScript code (and still can).4 This mechanism was
popular throughout the 1990s and 2000s because it worked. As more powerful
frameworks were developed, and website design and best practices were refined, this
original mechanism was supplanted by the listener approach.
A visual comparison of the old and new technique is shown in Figure 6.20.
Note how the old method weaves the JavaScript right inside the HTML, while the
listener technique has removed JavaScript from the markup, resulting in cleaner,
easier to maintain HTML code.
6.7.1 Inline Event Handler Approach
JavaScript events allow the programmer to react to user interactions. In early web
development, it made sense to weave code and HTML together and to this day,
inline JavaScript calls are intuitive. For example, if you wanted an alert to pop-up
when clicking a <div> you might program:
<div id="example1" onclick="alert('hello')">Click for pop-up</div>

6.7.2 Listener Approach


Section 6.2.1 argued that the design principle of layers is a proven way of increasing
maintainability and simplifying markup. The problem with the inline handler
approach is that it does not make use of layers; that is, it does not separate content
from behavior.
var greetingBox = document.getElementById('example1');
greetingBox.onclick = alert('Good Morning');
listing 6.10 The “old” style of registering a listener.

The approach shown in Listing 6.10 is widely supported by all browsers. The
first line in the listing creates a temporary variable for the HTML element that will
trigger the event. The next line attaches the <div> element’s onclick event to the
event handler, which invokes the JavaScript alert() method (and thus annoys the
user with a pop-up hello message). The main advantage of this approach is that this
code can be written anywhere, including an external file that helps uncouple the
HTML from the JavaScript. However, the one limitation with this approach (and
the inline approach) is that only one handler can respond to any given element
event.

var greetingBox = document.getElementById('example1');


greetingBox.addEventListener('click', alert('Good Morning'));
greetingBox.addEventListener('mouseOut', alert('Goodbye'));
// IE 8
greetingBox.attachEvent('click', alert('Good Morning'));
listing 6.11 The “new” DOM2 approach to registering listeners.

The examples in Listing 6.10 and Listing 6.11 simply used the built-in JavaScript
alert() function. What if we wanted to do something more elaborate when an
event is triggered? In such a case, the behavior would have to be encapsulated within
a function, as shown in Listing 6.12.

function displayTheDate() {
var d = new Date();
alert ("You clicked this on "+ d.toString());
}
var element = document.getElementById('example1');
element.onclick = displayTheDate;
// or using the other approach
element.addEventListener('click',displayTheDate);
listing 6.12 Listening to an event with a function

var element = document.getElementById('example1');


element.onclick = function() {
var d = new Date();
alert ("You clicked this on " + d.toString());
};
listing 6.13 Listening to an event with an anonymous function

6.7.3 Event Object


No matter which type of event we encounter, they are all DOM event objects and
the event handlers associated with them can access and manipulate them. Typically
we see the events passed to the function handler as a parameter named e.
function someHandler(e) {
// e is the event that triggered this handler.
}

function submitButtonClicked(e) {
if (e.cancelable){
e. preventDefault();
}
}
listing 6.14 A sample event handler function that prevents the default event

6.7.4 Event Types


Perhaps the most obvious event is the click event, but JavaScript and the DOM support
several others. In actuality there are several classes of event, with several types
of event within each class specified by the W3C. The classes are mouse events,
keyboard events, form events, and frame events.
Mouse Events
Mouse events are defined to capture a range of interactions driven by the mouse.
These can be further categorized as mouse click and mouse move events. Table 6.7
lists the possible events one can listen for from the mouse.
Interestingly, many mouse events can be sent at a time. The user could be moving
the mouse off one <div> and onto another in the same moment, triggering
onmouseon and onmouseout events as well as the onmousemove event. The Cancelable
and Bubbles properties can be used to handle these complexities.
Keyboard Events
Keyboard events are often overlooked by novice web developers, but are important
tools for power users. Table 6.8 lists the possible keyboard events.

These events are most useful within input fields. We could for example validate
an email address, or send an asynchronous request for a dropdown list of suggestions
with each key press.
<input type="text" id="keyExample">
The input box above, for example, could be listened to and each key pressed
echoed back to the user as an alert as shown in Listing 6.15.
listing 6.15 Listener that hears and alerts keypresses
document.getElementById("keyExample").onkeydown = function
myFunction(e){
var keyPressed=e.keyCode; //get the raw key code
var character=String.fromCharCode(keyPressed); //convert to string
alert("Key " + character + " was pressed");
}

Form Events
Forms are the main means by which user input is collected and transmitted to the
server. Table 6.9 lists the different form events.
The events triggered by forms allow us to do some timely processing in response
to user input. The most common JavaScript listener for forms is the onsubmit event.
document.getElementById("loginForm").onsubmit = function(e){
var pass = document.getElementById("pw").value;
if(pass==""){
alert ("enter a password");
e.preventDefault();
}
}
listing 6.16 Catching the onsubmit event and validating a password to not be blank

Frame Events
Frame events (see Table 6.10) are the events related to the browser frame that contains
your web page. The most important event is the onload event, which tells us
an object is loaded and therefore ready to work with. In fact, every nontrivial event
listener you write requires that the HTML be fully loaded.
However, a problem can occur if the JavaScript tries to reference a particular
<div> in the HTML page that has not yet been loaded. If the code attempts to set
up a listener on this not-yet-loaded <div>, then an error will be triggered. For this
reason it is common practice to use the window.onload event to trigger the execution
of the rest of the page’s scripts.
window.onload= function(){
//all JavaScript initialization here.
}

6.8 Forms
Chapter 4 covered the HTML for data entry forms. In that chapter it was mentioned
that user form input should be validated on both the client side and the
server side.
To illustrate some form-related JavaScript concepts, consider the simple HTML
form depicted in Listing 6.17.
6.8.1 Validating Forms
Form validation is one of the most common applications of JavaScript. Writing code
to prevalidate forms on the client side will reduce the number of incorrect submissions,
thereby reducing server load. Although validation must still happen on the
server side (in case JavaScript was circumvented), JavaScript prevalidation is a best
practice. There are a number of common validation activities including email validation,
number validation, and data validation.

Empty Field Validation


A common application of a client-side validation is to make sure the user entered
Something into a field. There’s certainly no point sending a request to log in if the
username was left blank, so why not prevent the request from working? The way to
check for an empty field in JavaScript is to compare a value to both null and the
empty string ("") to ensure it is not empty, as shown in Listing 6.18.

Some additional things to consider are fields like checkboxes, whose value is
always set to “on”. If you want to ensure a checkbox is ticked, use code like that
below.
var inputField=document.getElementByID("license");
if (inputField.type=="checkbox"){
if (inputField.checked)
//Now we know the box is checked, otherwise it isn’t
}

Number Validation
Number validation can take many forms. You might be asking users for their age
for example, and then allow them to type it rather than select it. Unfortunately, no
simple functions exist for number validation like one might expect from a fullfledged
library. Using parseInt(), isNAN(), and isFinite(), you can write your
own number validation function.

6.8.2 Submitting Forms


Submitting a form using JavaScript requires having a node variable for the form
element. Once the variable, say, formExample is acquired, one can simply call the
submit() method:
var formExample = document.getElementById("loginForm");
formExample.submit();
This is often done in conjunction with calling preventDefault() on the onsubmit
event. This can be used to submit a form when the user did not click the submit
button, or to submit forms with no submit buttons at all (say we want to use an
image instead). Also, this can allow JavaScript to do some processing before submitting
a form, perhaps updating some values before transmitting.

You might also like