You are on page 1of 59

CS3 LEARNING MODULE

Campus: PSHS-CVisC

Grade Level: 9
Subject / Topic: CS3 / HTML Forms
Time Frame: 250 minutes

Target Number of Sessions: 5

Resources / Materials Needed:


Internet Access and Internet-ready devices
PREFACE

Good day, Pisay students!

In response to the COVID-19 Pandemic, this module was


created to facilitate your continued learning of the remaining
Computer Science 3 topics of the 4th Quarter, A.Y. 2019 –
2020.

This module can be accomplished without the need of any


face-to-face interactions with the subject teacher. All
resources and lecture materials, are either bundled in digital
form, or are linked (if they are on the internet).

We value both your safety and your quality of education. May


this module serve its purpose well.

Photo by Jire Carreon/Rappler 2


REQUIREMENTS

To unlock the full potential of this learning module, you will


need the following materials and resources:

ACCESS TO THE INTERNET COMPUTER OR SMARTPHONE CODE EDITOR

You need to have access to the internet to A device, which can be a computer or a This is OPTIONAL, but if you want to do
be able to view online resources like smartphone, will be needed to view the hands-on coding (which can be helpful),
tutorials, samples, etc. However, these will lecture materials and any resources like you can do so by installing a code editor
be supplementary resources only. You will videos, e-books, etc. If you have access to on your computer. An example of a code
still be able to learn a lot using the bundled the internet at home, your device must also editor would be Visual Studio Code and
resources and materials. be able to utilize this. Notepad++.

3
TOPICS
For the 4th and final quarter, you will be learning about HTML Forms. The term
may seem unfamiliar, but HTML forms are ubiquitous. You may have come
across them plenty of times!

This main topic will be divided into four chapters/subtopics:

HTML FORM CONTROLS


Creating an HTML Forms is like building with Legos. There are many different
types of building blocks called “form controls” that you mix together to create a
form for specific purposes and types of data.

HTML FORM PROPERTIES


There are many things you can do to your form fields. You can set default values,
hide or disable them. All that good stuff!

HTML FORM HANDLING


Using a little bit of JavaScript, we can detect user interactions to our form like
clicks, changes, submissions, and more. We can do something in code when that
happens too.

USER INPUT VALIDATION


“Your password must be at least 8 characters long.” We can do that as well and
much more!
Sign up form UI/UX design by Andrew Smarius
https://dribbble.com/shots/7309810-Sign-Up-Form 4
GOING BEYOND

This learning module will gloss over a lot of details especially in later topics. This is to make the module
compact and less intimidating for those students that are not into advanced programming.

You’ll occasionally come across links to online resources as you move along the topics. If you are
interested in learning more about the topics and you have access to the internet, it is highly This is a screenshot of the MDN Web Docs website featuring their step-
encouraged that you visit them. by-step guide and tutorial on creating HTML forms.

For those students who really want to develop and improve their web development skills and
knowledge, you can learn more advanced topics in more detail by reading and following the guides
and written tutorials in Mozilla Developer Network’s (MDN) website. Most of the information here are
sourced from their web docs. This website is maintained by the people behind the Mozilla Firefox web
browser. Pretty cool! This is the official link: https://developer.mozilla.org

If you specifically want to learn about making HTML forms, the MDN website has a step-by-step
tutorial on this topic, which is good for beginners.
You can visit it here: https://developer.mozilla.org/en-US/docs/Learn/Forms
5
If you are all set,

LET’S BEGIN!

6
Photo Credit: REUTERS/Pierre Ducharme
<html-form-controls/>

7
OBJECTIVES

At the end of this chapter, you should be able to:

explain what HTML forms are, how they are used in web applications, and their
advantages and disadvantages over paper-based forms

understand how HTML form controls are used to build HTML forms, and be able to
choose the appropriate form controls for the type of user input

generate the different HTML form controls by typing their corresponding HTML
tags in code using a text editor and view the results in an internet browser

8
What are HTML Forms?

As frequent users of the world wide web and the internet, you may have come across
These are Facebook’s login and registration forms on their official
HTML Forms plenty of times. People sometimes refer to them as “online forms” or
website facebook.com. They can only be seen by non-registered users
“web forms”. They are one of the many ways web apps gather data from their users. and users who have not logged in.

Here are the most common applications of HTML forms:

Enable a user to register to a website and become a registered user (“member”)


of a website. The registration process usually involves gathering data from the
user.

Enable a user to “log in” and access the services of a website that are only for its
registered users. This is usually done by asking the user for a unique combination
of a username and a password.

Enhance the capability of a web application by allowing the users to input data in
the app itself. A social media application, for example, usually has an HTML form
that you can use to create a public “post”. An email service may have a form
where you can compose emails and specify its recipients.

9
HTML Forms vs. Paper-based Forms

HTML Forms are based on printed, paper-based forms. Before the advent of
graphical user-interface and the web, filling out forms on paper was the norm.

HTML forms offer some advantages to their paper-based counterparts:

They do not use paper.

They can be more accessible to users who can not obtain the paper-based forms
in person.

They can be more flexible, especially if the user wants to put in a lengthy input.
Paper can run out of space.

They can be made more compact and space-efficient. This is especially true if the
form involves making a user choose from a huge set of options (like choosing a
country from a list).

They also have some disadvantages:

You will need a computer (and internet access), and some computer literacy to
be able to view, understand, and interact with them.

Some of the most common features of paper-based forms, like signatures, can be
tricky to mimic in HTML forms.
10
HTML Form Controls

HTML Forms are made up of simple building blocks, with many different types –
like Lego pieces! They are called HTML Form Controls, or “form controls” for
short. They are also referred to as widgets. Here, they’ll be called form controls,
so keep this in mind.
Option 1 Option 2
What form controls you use in a form depends on the types of data you want to
get from the user. Is it a simple text input? Is it short text? A long text? Is it a
password input? Does the user choose an item from a small set of options? Or an
item from a huge set of options?

In the following pages, you’ll learn some of the most common form controls and
the purposes they serve.
HTML CODE

QUICK INFO <!DOCTYPE html>


<html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
</head>
Before you proceed to learning the different HTML Form Controls, please take note of <body>
<form>
the following: <label>ENTER YOUR USERNAME:</label>
<input type="text"/>
<label>ENTER YOUR PASSWORD:</label>
Whenever you are presented with a browser preview of the result of a sample HTML <input type="password">
code like what you see on the right, remember that this is a direct screen snippet <input type="submit" value="LOGIN"/>
</form>
(cropped screenshot) of the browser Mozilla Firefox (version 76) running on Microsoft </body>
</html>
Windows 10.
BROWSER VIEW

The result you’d get from the sample code may look different depending on what
browser you are using (Firefox, Chrome, Safari, Edge, etc.), what operating system the
browser is running on (Windows, MacOS, Android, etc.), and what device you are using
(smartphone, laptop/desktop).

A button in Mozilla Firefox may look different from a button in Google Chrome, but
both will (more or less) behave in the same way.
HTML CODE

<!DOCTYPE html>

FORM TAG <html>


<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
The form tag is not really a form control, but rather the foundation upon which the
</head>
form controls will be built. Whenever you want to create a HTML form, you always start <body>
it with a <form></form>. <form>
<!-- we build our form in here! -->
</form>
When you view the sample HTML code in the browser, it will be empty. This is expected,
</body>
as the form tag doesn’t actually display anything. It is just an indication that you are </html>
about to create a form. In more advanced topics, you’ll see why this is needed. Let’s not
worry about that, for now. BROWSER VIEW

Inside this pair of opening and closing form tag is where you’ll put your form controls.
You can also put inside a lot of the HTML tags you’re already familiar with, like
<div></div>, <span></span>, <p></p>, <h></h>.

If you want to learn more about the form tag and what other tags that
can be put inside it, visit:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form

white void, as expected…


HTML CODE

<!DOCTYPE html>

TEXT FIELD <html>


<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
A text field provides an area for the user to type and enter text-based data.
</head>
<body>
<form>
TheLegend27 <input type="text"/>
</form>
</body>
To create a text field in your form, you type <input type="text"/> in your HTML </html>
code.
BROWSER VIEW

Typically, text fields (also called “text boxes”) are used for inputs like names,
usernames, words, phrases, and sentences. Anything longer than these (such as a
paragraph) will make the text field impractical to use. Fortunately, there is another form
control for long text inputs!

You may have to use CSS to


override the default, boring
look of your text field.
HTML CODE

<!DOCTYPE html>

PASSWORD FIELD <html>


<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
A password field allows the user to enter sensitive and private text-based data such as a
</head>
security code or a password. <body>
<form>
<input type="password"/>
</form>
</body>
</html>
To create a password field in your form, you type <input type="password"/> in
your HTML code. BROWSER VIEW

In almost all browsers, whenever the user enters a text in a password field, the
characters are replaced with asterisks, dots, or circles to protect the information from
onlookers. In some browsers, this feature can be turned on or off with a toggle (usually
an “eye” icon beside the field itself).
HTML CODE

<!DOCTYPE html>

LABELS
<html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
</head>
As the name suggests, labels are used to label things in a form. You can use labels to
<body>
indicate the information you are asking from the user. A label can be put beside text <form>
<label>Enter your username: </label>
fields, password fields, and many other form controls.
<input type="text" />
</form>
</body>
To create a label in your form, type <label></label> in your HTML code. The actual </html>
text of the label is put between the pair of tags. See the sample code on the right.

BROWSER VIEW
HTML CODE

<!DOCTYPE html>

RADIO BUTTONS
<html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
</head>
Are you a student or a teacher? When a user has to make a choice from a small set of
<body>
options, radio buttons are the way to go! <form>
<input type="radio" name="personality">
<label>Introvert</label>
<input type="radio" name="personality">
Student Teacher <label>Extrovert</label>
<input type="radio" name="personality">
<label>Ambivert</label>
To create a radio button in your form, type </form>
</body>
<input type="radio" name="choices"> in your HTML code. </html>

BROWSER VIEW
The name property is important. It’s value can be whatever you like (as long as it’s a
string with no spaces). Radio buttons with the same name values belong to the
same set of options. What happens when you give each of your radio buttons different
name values?

DID YOU KNOW?


The term “radio button” is a reference to the punch-in
buttons invented years ago on radios to choose a preset
station. As each new button is pressed, the previously
pressed button is returned to the neutral position.
HTML CODE

<!DOCTYPE html>

CHECKBOX <html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
Checkboxes function similar to radio buttons. However, a set of checkboxes allow the </head>
user to select multiple items from a set of options. <body>
<form>
<input type="checkbox">
<label>
Show Date To create a checkbox in your form, type
I agree to the terms and conditions
<input type="checkbox"> in your HTML code. blah blah blah...
Show Month </label>
You then use a <label></label> to put a label
</form>
Show Year beside your checkbox.
</body>
</html>
A checkbox is also commonly used to get a confirmation from the user, such as in BROWSER VIEW

agreeing to a website’s terms of service (TOS) or privacy policy. See the sample code on
the right to see how it’s done at the most basic level.

DID YOU KNOW?


If you’ve used mobile apps or mobile operating
systems like Android and iOS, you may have come
across these virtual switches called “toggles”. These
are basically more touch-friendly versions of
checkboxes! More and more apps and websites try to
adopt toggles in their design.
HTML CODE

<!DOCTYPE html>

BUTTON
<html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
</head>
Form buttons mimic real-life buttons and are used for “one-click” functionalities.
<body>
<form>
<!-- using the <input> tag -->
Refresh <input type="button" value="Save Data"/>
<!-- using the <button> tag-->
<button>
<img src="check.png">
There are two ways of creating a button in HTML. Save Data
The first method is using <input type="button"> like below: </button>
</form>
</body>
<input type="submit" value="Refresh"> </html>

BROWSER VIEW
The second method is by using the <button></button> tags, like so:

<button>Refresh</button>

The advantage of using the second method is that you put HTML code inside the pair
of <button></button> tags. For example, you can put an image to serve as an icon
for the button. Take a look at the example on the right.
HTML CODE

<!DOCTYPE html>

SUBMIT BUTTON
<html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
</head>
A submit button is a special button that serves a specific purpose – to “submit” all the
<body>
data gathered within the form to a destination. The “destination” is usually a server, <form>
<label>
where the data can be stored and processed.
Please enter your name:
</label>
<input type="text">
Submit <input type="submit" value="Submit">
</form>
</body>
</html>
If you don’t specify a text in the value property of a submit button, your browser will
usually set a default text inside the button. In Mozilla Firefox, “Submit Query” is the
BROWSER VIEW

default text.

IMPORTANT

To be able to serve its purpose, a submit button must be put within a


<form></form>. Also, a submit button will only submit the data from the
form it is in. That is, if you have multiple forms in your page, each of them will
require their own separate submit buttons!
HTML CODE

<!DOCTYPE html>

TEXT AREA
<html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
</head>
When you want the user to be able to enter a very long text data, like a comment or a
<body>
paragraph, a simple text field will not be practical. A text field is only good for single- <form>
<textarea></textarea>
line text data. Multiple lines of text is best handled by a text area.
</form>
</body>
</html>
There is a feeling of tranquility living on top of a mountain
overlooking the sea. It has long been my dream...

BROWSER VIEW
To create a text area in your form, type <textarea></textarea> in your HTML code.

A text area can accommodate text both horizontally and vertically. A scroll bar will
appear if the user’s text input has exceeded the viewing area. In some browsers, text
areas can be resized by the user to delay the need for the scroll bar. Neat!
HTML CODE

<!DOCTYPE html>

DROPDOWN MENU
<html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
</head>
Sometimes called a list-box, a dropdown menu is an alternative to radio buttons in <body>
<form>
cases where the user has to select an item from a long list of options. <select>
<option>Argentina</option>
<option>Armenia</option>
<option>Bolivia</option>
Select a Country <option>Burkina Faso</option>
<option>Canada</option>
</select>
Afghanistan </form>
</body>
Armenia </html>
Bolivia
Burkina Faso BROWSER VIEW

To create a dropdown menu in your form, type <select></select> in your HTML


code. To populate the dropdown menu with options, you use the <option></option>
tags. See the sample code on the right.

A dropdown menu helps keep an online form compact by displaying the list of options
only when needed. Different apps and operating systems have different
implementations of the dropdown menu, but the principle and purpose remains the
same.
HTML CODE

<!DOCTYPE html>

FIELDSETS & LEGENDS


<html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
</head>
Fieldsets and legends can be useful for grouping and organizing a section of your <body>
<form>
HTML form. They help give your form some structure. <fieldset>
<legend>LOG IN</legend>
<label>Username: </label>
<input type="text">
BASIC INFORMATION
<label>Password: </label>
<input type="password">
<input type="submit" value="Submit">
</fieldset>
</form>
</body>
</html>
EDUCATIONAL BACKGROUND
BROWSER VIEW

To put a section of your form inside a group, put them inside a


<fieldset></fieldset>. This will create a border around the specified section of
your form. The <legend></legend> is optional, but can be helpful for labeling the
different sections in a big, multi-sectioned form.
HTML CODE

TRY IT! <!DOCTYPE html>


<html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
<link rel="stylesheet" href="login_form.css">
You can make your form look good using CSS! </head>
<body>
<form>
CSS CODE <label>Username: </label>
<input type="text">
body { <label>Password: </label>
font-family: Arial; <input type="password">
} <input type="submit" value="Submit">
</form>
label { </body>
font-weight: bold; </html>
font-size: 0.8em;
} BROWSER VIEW

input {
border: 1px solid seagreen;
height: 25px;
box-sizing: border-box;
}

input[type="submit"] {
background-color: seagreen;
color: white;
font-size: 0.8em;
}
CHALLENGE

Try creating this HTML form using HTML and CSS. Make sure to use the proper form controls.
CHALLENGE

Try creating this HTML form using HTML and CSS. Make sure to use the proper form controls.
Text Field

Password Field

Radio Buttons
Password Field

Checkbox

Dropdown Menu

Submit Button
RECALL

Explain the purpose of each of the following form controls: Text Field, Password Field,
1
Radio Buttons, Checkbox, Buttons, Submit Button, Dropdown Menu, and Text Area.

For a text data like a tweet in Twitter, which form control will you use to get
2
the text data from the user? A text field or a text area? Explain.

3 Why does a password field replace the user’s text input with asterisks or circles?

In a buy and sell website form, the user must be able to choose condition of the item he or
4 she is selling. There are only two options: Permanent and Current. Which form control is best
suited for this scenario? Why?

In the same buy and sell website, whenever a user tries to sell a phone, the user can specify the
5 manufacturer or brand of the phone. The options include Apple, Samsung, Asus, LG, Nokia, and
many more. Which HTML form control is best suited for this user input?
27
EXPLORE

There are many more form controls that you can try! The MDN website have a very useful tutorial on all of them. You
can learn about them here: https://developer.mozilla.org/en-US/docs/Learn/Forms/HTML5_input_types
<html-form-properties/>

29
OBJECTIVES

At the end of this chapter, you should be able to:

determine the commonly-used HTML form properties and what they are used for

apply the HTML form properties to accomplish tasks like: settings default values to
form controls, disabling form controls, preselecting options, and hiding form
controls from view

30
What are form properties?

In the previous chapter, we came across this HTML Code: Observe this line of code:

HTML CODE
<input type="submit" value="Submit">
<!DOCTYPE html>
<html>
<head> There is an HMTL property (also called “attribute”) named value
<meta charset="utf-8">
that specifies the piece of text you’d want to appear on the
<title>HTML Form Tags</title>
</head> submit button.
<body>
<form>
<label> value is one of several HTML properties that are made especially
Please enter your name:
</label> to help in creating HTML forms, hence the term form properties.
<input type="text">
<input type="submit" value="Submit">
</form> In the following slides, you’ll be introduced to the commonly
</body> used form properties and their uses.
</html>

This is the HTML code for demonstrating the use of a submit button in
an HTML form (see slide #19).

31
HTML CODE

<!DOCTYPE html>

VALUE
<html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
</head>
The property value, aside from enabling us to customize the text in buttons, can also be
<body>
used to set default values to form controls that accept text-based user inputs. <form>
<label>Enter a username: </label>
<input type="text" value="thelegend27"/>
Below are examples of how you can use the value property in text and password fields:
</form>
</body>
</html>
<input type="text" value="thelegend27"/>

<input type="password" value="123456"/>

However, if you try to use this property to set a default value for a text area, it will not BROWSER VIEW

work:

<textarea value="This is the default text"></textarea>

This is something to be careful about! To set a default value for a text area, you put it
inside the tags, like this:

<textarea>This is the default text</textarea>

What do you think is the use or purpose of setting a default value to text fields?
HTML CODE

<!DOCTYPE html>

DISABLED <html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
Let’s say you want to block the user from interacting with a form control (like a text field
</head>
or checkbox) until a certain condition in your JavaScript code is met. Fortunately there is <body>
also a form property for that! <form>
<label>Enter a username: </label>
<input type="text" disabled/>
As an example, to disable a text field, you simply add the word “disabled” within its
</form>
HTML tag: </body>
</html>
<input type="text" disabled/>

BROWSER VIEW
The browser then blocks any interaction with the text field. The user cannot click and
type on a disabled field.

You can also disable a text area the same way:

<textarea disabled></textarea>

To learn more about the disabled property and what form controls you can use
it for, visit:
https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/disabled
HTML CODE

<!DOCTYPE html>

SELECTED
<html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
</head>
To preselect an option from a dropdown menu after the page loads, you use the <body>
<form>
selected property. <select>
<option>Argentina</option>
<option selected>Armenia</option>
The selected property is similar to that of value, but for dropdown menus. To specify the <option>Bolivia</option>
option you want preselected, simply put the word “selected” in the corresponding <option>Burkina Faso</option>
<option>Canada</option>
<option> tag. Like so: </select>
</form>
</body>
<option selected>Armenia</option> </html>

BROWSER VIEW

IMPORTANT

You may need to do a “hard reload” on your browser for this property to work. This is
not a bug with the selected property itself, but rather a browser “feature” that’s actually
meant to make page loads faster. This feature can sometimes interfere with this
property.
HTML CODE

<!DOCTYPE html>

HIDDEN <html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
Yup. You guessed that right. The hidden property is used to hide form controls. </head>
<body>
<form>
To hide a form control, like a text field for example, simply put the word “hidden” in the <label>Username: </label>
HTML tag of the form control you want to hide. Like this: <input type="text" hidden/>
<label>Password: </label>
<input type="password">
<input type="text" hidden/> <input type="submit" value="Login">
</form>
</body>
</html>
Hidden form controls let you include data that cannot be seen or modified by users
when a form is submitted. BROWSER VIEW

IMPORTANT

Changing the value of the CSS display property on a form control with the hidden
property on its HTML tag will override (cancel) the behavior of the HTML property. For
example, a text field configured like below will be visible:

<input type="text" hidden style="display: inline"/>

Notice that the text field for the


username is missing
RECALL

Which of the following form control does the property selected work with?
1
a. Radio Buttons
b. Checkbox
c. Dropdown Menu
d. Text Field

Which of the following code is the correct way of setting a default value of a text
2
area?
a. <textarea value="This is the default text"></textarea>

b. <textarea>This is the default text</textarea>

3 Which form property blocks any interaction by the user to a form control?
a. hidden
b. disabled
c. selected
d. value
36
<html-form-handling/>

37
OBJECTIVES

At the end of this chapter, you should be able to:

explain how to detect user interactions with your HTML form such as when the
user clicks, make changes, or submits the form

link a JavaScript function such that it is called every time the user interacts with a
form control

38
Detecting User Interactions

So far, you’ve been able to create simple HTML forms, styled with CSS, and
further enhanced with HTML form properties. BROWSER VIEW

This is all well and good. However, the power of HTML forms is that they
can be programmed. You can program a text field such that it gives out an
error if the user enters an invalid piece of text. You can program a password
field to accept only passwords that are at least 8 characters long.

To achieve such functionalities, you first have to be able to detect whenever


a user interacts with your form controls. Did the user click the button? Is the
user typing something in the text field? Has the user selected an option from
the dropdown menu? These are called events. When you do something in
your program when an event happens, this is called event handling.

This is where JavaScript comes in handy. JavaScript was made primarily for this
A simple login form you’ve previously made.
purpose. It’s often referred to as an event-driven programming language. Aha!

39
HTML CODE

<!DOCTYPE html>

ONCLICK <html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
To detect when a user clicks a form control, you use the onclick event. <script src="events.js"></script>
</head>
<body>
<form>
<input type="button"
value="Click Me!"
onclick="buttonClicked()"/>
Below is an example of how the onclick event is used: </form>
</body>
</html>
<input type="button" value=“Click Me!" onclick="buttonClicked()"/>

Notice that the value of the onclick property (inside the pair of quotes) is a function call. JAVASCRIPT CODE

Remember function calls in JavaScript? // this is our event handler


function buttonClicked() {
This means that the way for you to detect when the text field is clicked is by making a alert(“The button was clicked!")
}
JavaScript function, and setting it as the value of the onclick event. This JavaScript
function then becomes the event handler.

The onclick event can be used for all form controls – button, dropdown menu, text area,
as well as non-form-related HTML elements like <body>,<div>,<img>, etc.
HTML CODE

<!DOCTYPE html>

ONCHANGE <html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
The onchange event is triggered every time the user changes the value of a form control <script src="events.js"></script>
like a text field or a dropdown menu. </head>
<body>
<form>
TheLegend27 <input type="text"
onchange="textChanged()"/>
</form>
</body>
<input type="text" onchange="textChanged()"/> </html>

Just like the previously-shown onclick event, we set a JavaScript function as an event
handler for the onchange event. JAVASCRIPT CODE

The onchange event can only be applied to <input>, <select>, and <textarea>. // this is our event handler
function textChanged() {
alert(“The text was changed by the user!")
IMPORTANT }

The change event is not necessarily triggered for each alteration of a form control’s value.
Depending on the kind of form control being changed and the way the user interacts it, the
onchange event is triggered at a different moment. To learn the details of this behavior, visit
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
HTML CODE

<!DOCTYPE html>

ONSELECT <html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
The onselect event is triggered every time the selects a piece of text inside a text field or <script src="events.js"></script>
a text area. </head>
<body>
<form>
There is a feeling of tranquility living on top of a mountain <input type="text"
onselect="textSelected()"/>
overlooking the sea. It has long been my dream... </form>
</body>
</html>

Below is an example of using the onselect event for a text field:

JAVASCRIPT CODE

<input type="text" onselect="textSelected()"/>


// this is our event handler
function textSelected() {
The same event can also be used for a text area: alert(“A text was selected in the text field!")
}
<textarea onselect="textSelected()"></textarea>
HTML CODE

<!DOCTYPE html>

ONFOCUS <html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
The onfocus event is triggered when the user sets focus on an <input> form control. <script src="events.js"></script>
</head>
<body>
TheLegend27 <form>
<input type="text"
onfocus="textFieldFocused()"/>
</form>
At first glance, the onfocus event seems identical similar to the onclick event, but there </body>
are two notable differences: </html>

The onfocus event only applies to <input> controls, by default. There is a way to
make this event applicable to other HTML tags, but this is already outside the JAVASCRIPT CODE

scope of what you have to learn, for now.


// this is our event handler
function textFieldFocused() {
A form control, such as a text field, can also trigger the onfocus event when it gains console.log("The text field has gained focus!")
focus via the TAB key on the user’s keyboard. You might be familiar with the method }
of filling up forms using the TAB key to move from one input field to the next.

In browsers like Google Chrome, the browser puts a “glow” or distinct border style to a
form control that has gained focus. This behavior can be overridden or enhanced in CSS
should the designer want to do so.
We use console.log here because an alert pop-up
will make the element lose the focus.
HTML CODE

<!DOCTYPE html>

ONBLUR <html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
The onblur event is triggered when an <input> form control loses focus. <script src="events.js"></script>
</head>
<body>
TheLegend27 <form>
<input type="text"
onblur="textFieldBlurred()"/>
</form>
An form control will lose focus when the user clicks outside of it or when the user focus </body>
on another form control (either via a mouse click or via the TAB key). </html>

The onblur event is the opposite of onfocus. JAVASCRIPT CODE

// this is our event handler


function textFieldBlurred() {
console.log("The text field has lost focus!")
}
RECALL

Recall as much details as you can about each of the following form events:
1
onclick, onchange, onselect, onfocus, and onblur

2 Explain the two major differences between the onfocus and onclick events.

TRUE or FALSE: The onfocus event can be applied to other form controls other than those
3
using the <input> tag.

4 Why is JavaScript classified as an event-driven programming language?

45
<user-input-validation/>

46
OBJECTIVES

At the end of this chapter, you should be able to:

explain what “user input validation” is and how events and event handlers help
enhance the capabilities of our HTML forms

identify a few examples of simple user input validations using JavaScript

create custom user input validations in your custom HTML forms

47
What is User-Input Validation?

If you try to be very observant while surfing the web, you may notice error
messages in HTML forms like the one on the right.

Then you’ll realize such functionalities are very everywhere in the web! How many
have you been frustrated trying to think of a password that must have letters,
numbers, and special characters just to be able to register?

However, these restrictions and checks on the user’s input do serve an important purpose.
The process of checking user inputs is called user-input validation or more commonly,
form validation. Here are three reasons why it is important and why, if you ever use HTML
forms, you should also do it:

You want to get the right data, in the right format. Your application may not work
properly if your users' data is stored in the wrong format, is incorrect, or is omitted
altogether.

You want to protect your users' data. Forcing your users to enter secure passwords makes
it easier to protect their account information.
Twitter’s Sign Up form incorporates user-input validation
Security for your application. There are many ways that malicious users can misuse
unprotected forms to damage the application. Never trust data you receive from your users!
48
Screenshot of article by The Guardian about the self-retweeting tweet and
WATCH Twitter’s response to the events. Article Link:
https://www.theguardian.com/technology/2014/jun/12/tweetdeck-
vulnerability-teen-code-emoji-heart
On June 2014, a teenager made headlines when he found a security flaw (or a bug,
some may say) when he was able to create a “self-retweeting” tweet. It was a classic
example of how a simple mistake of not doing form validation can wreck havoc to a
web application. The teenager used what is called Cross-Site Scripting (XSS) attack.
Read the article about this event and watch the video on why it happened!

Popular Youtuber Tom Scott explains how the Self-Retweeting Tweet worked.
Video Link: https://www.youtube.com/watch?v=zv0kZKC6GAM
User changes the value of form control

Event Handlers and Validation


hi
In the previous chapter, you learned how to detect user interactions and
changes in your HTML form.

JAVASCRIPT CODE

// this is our event handler onchange event triggered


function textSelected() {
alert(“A text was selected in the text field!")
}

A simple JavaScript function you’ve previously tried using as an event


Check if the value follows the appropriate format.
handler for the onselect event

The JavaScript functions you used to process the events were very simple.
They don’t yet serve much of a purpose apart from testing whether the
events were triggered in your HTML form. We can make them useful by
making them do form validations!
Inform user of validation result

To do this, you must first learn how to get the user input in JavaScript. How hi
do we access the value of a form control after the user has changed its
Error: Username must be at least 4 characters long…
value?

50
Accessing the Value

To be able to perform any form validation, you must first be able to access the value of a form control. A bit of
modification to your previous code and you’ll be able to do this every time an event like onchange is triggered.

STEP 1 STEP 2
First, you need to pass a variable named event to the event Then, you “receive” the value of the variable you just passed to
handler of your onchange event: your event handler by modifying the JavaScript function to accept
HTML CODE an input (or parameter). Let’s call this input event to make it clear.
<!DOCTYPE html> You can name this whatever you like.
<html>
JAVASCRIPT CODE
<head>
<meta charset="utf-8"> // this is our event handler
<title>HTML Form Tags</title> function textChanged(event) {
<script src="events.js"></script> // let’s test by alerting the value
</head> alert(event.target.value)
<body> }
<form>
<input type="text"
onchange="textChanged(event)"/> And that’s it! Try changing the value of the text field and you
</form>
</body> should see an alert pop-up bearing the exact same text you just
</html> typed!

51
Validation Example JAVASCRIPT CODE

function checkPassword(event) {
let password = event.target.value
Let’s take a look at a simple example of user input validation. In this
if (password.length < 8) {
example, you have to check whether the password the user typed is alert("Your password must be at least 8 characters long.")
}
at least 8 characters long. If not, you have to show an error
}
message.

BROWSER VIEW

HTML CODE

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
<script src="events.js"></script>
</head>
<body>
<form>
<input type="password"
onchange="checkPassword(event)">
</form>
</body>
</html>
JAVASCRIPT CODE

function checkPasswordsMatch(event) {

Accessing Multiple Form Controls


let confirm_pass = event.target.value
let pass = document.getElementById('password').value
let error_msg = document.getElementById('error_msg')
You can also access the values of form controls without having to
if (confirm_pass != pass) {
receive an event in your event handler. This is useful when you want to error_msg.removeAttribute('hidden')
}
get the value of another field for processing (like a comparison).
else {
error_msg.setAttribute('hidden', true)
In this example, whenever the user changes the value of the “Confirm }
}
Password” field, you inform the user if the value matches that of the
“Password” field. For the error message, you can use a <span> and HTML CODE

hide or show it using the hidden property you’ve learned earlier! <!DOCTYPE html>
<html>
BROWSER VIEW <head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
<script src="events.js"></script>
</head>
<body>
<form>
<label>Password: </label>
<input type="password" id="password"/>
<label>Confirm Password: </label>
<input type="password" id="confirm_password"
onchange="checkPasswordsMatch(event)">
<div>
<span id="error_msg" hidden>
Passwords do not match!
</span>
</div>
</form>
</body>
</html>
JAVASCRIPT CODE

TRY IT! function checkSpaces(event) {


let username = event.target.value
// fill in code
You have to detect whether the username the user has chosen does
not contain any spaces. If it does, you inform the user that this is
not allowed.
}
Fill in the JavaScript code to make this feature.
BROWSER VIEW

HTML CODE

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML Form Tags</title>
<script src="events.js"></script>
</head>
<body>
<form>
<input type="text"
onchange="checkSpaces(event)">
</form>
</body>
</html>
CHALLENGE

Continuing the registration form you made from the previous challenge, try to
add some form validations to make your form more interactive!

Here are the rules and constraints you have to implement:

Username must be at least 4 characters long, and at most 20 characters long.

Username must not contain any spaces.

Password must be at least 8 characters long.

The “Confirm your Password” field must match the previous password field

Here’s an additional challenge:

The submit button must only be enabled if all the fields in the form are filled out
correctly with no errors and no fields skipped.

The error messages must be displayed on the form itself. Do not use alerts or
console logs.
EXPLORE

You can create simple form validations without writing any JavaScript code. You read that right! If you want to learn
how to do this and more, visit: https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation
57

Congratulations! You’ve reached

THE END.

Photo Credit: NASA


CREDITS

Huge shoutout to Icons8 where all of the icons and vector graphics used in this learning To learn web development and enhance your coding skills in HTML, CSS, or JavaScript, visit
module was downloaded from. Visit Icons8.com and download awesome icons for free! the MDN website (now named MDN Web Docs): https://developer.mozilla.org/en-US/

58
Prepared by: Mark Lester Canubas

Recommending Approval:

Arlo S. Chavez Joseph P. Hortezuela


Unit Head, CS-TechEngg. CID Chief

Approval:

Rachel Luz V. Rica, PhD


Campus Director

You might also like