You are on page 1of 65

HTML

Forms Dr Martins E. Irhebhude

1
Introductio
• In general, if you want to collect vital information
nabout someone or something, the form is used.
• What if you want to create a Web page which will
collect data from the user? You can collect data
from the users of your Web site by using forms.
For instance, you can ask users to fill out forms to
specify which products they want to order. You
can also use forms to collect feedback about your
site.
• HTML forms are placed on a web page using the
<form></form> tag. This tag should encapsulate a
series of other form elements, identifying them as
a single cohesive web form.
Introductio
•nHTML form elements rely on action and
method attributes to identify where to
send the form data for processing
(action) and how to process the data
(method).
• Unfortunately, HTML alone is unable to
process form data. A scripting language
such as PHP, PERL, and/or JavaScript
must be used with HTML forms to
process data captured by HTML form
elements
The <input> Element
• The <input> element is the most
important form element.
• The <input> element has many
variations, depending on the type
attribute.
Types of input element
Type Description
text Defines normal text input
radio Defines radio button input (for
selecting one of many choices)
submit Defines a submit button (for
submitting the form)
Example
<form>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
</form>
Radio Button Input
• <input type="radio"> defines a radio
button.
• Radio buttons let a user select ONE of a
limited number of choices:
<form>
<input type="radio" name="sex"
value="male" checked>Male
<br>
<input type="radio" name="sex"
value="female">Female
</form>
checkbox forms
Setting the type attribute of an <input> tag to checkbox places a
checkbox element onto the web page.
<form name="myWebForm" action="mailto:youremail@emai
l.com" method="post">
<p>Please select every sport that you play.</p>
Soccer: <input type="checkbox" name="sports"
value="soccer" /><br /> Football: <input
type="checkbox" name="sports"
value="football" /><br /> Baseball: <input
type="checkbox" name="sports"
value="baseball" /><br /> Basketball: <input
type="checkbox" name="sports"
value="basketball" />
</form>
Password Fields
HTML password fields are designed to capture
user input, but disguise each character with an
asterisk (*) instead of displaying the entered
digits. They offer a user on-screen privacy while
he or she is entering a password.
<form name="myWebForm" action="mailto:
youremail@email.com" method="post">
Password: <input type="password"
title="Please Enter Your Password"
size="8" /><br />
<input type="submit" value="SUBMIT" />
</form>
<form name="myWebForm" action="mailto:y
ouremail@email.com" method="post">
First: <input title="Please Enter Your First
Name" id="first" name="first" type="text"
size="12" maxlength="12" /> Last: <input
title="Please Enter Your Last Name" id="last"
name="last" type="text" size="18"
maxlength="24" /><br />
Password: <input type="password"
title="Please Enter Your Password" size="8"
maxlength="8" /><br />
<input type="submit" value="SUBMIT" />
</form>
• Password fields offer a very thin
layer of security by visually
concealing passwords; they
offer no security whatsoever
against maintaining the integrity
of the password data.
• Form data is processed in plain
text and can be readily sniffed
by a hacker, unless HTTPS is
used to encrypt the data.
reset buttons
• A reset button allows users
to basically clear their web
form.
• It wipes values from all
fields by "resetting" the
form to its default
appearance.
upload forms
• Upload fields provide the interface that allows users
to select a local file and upload it to the web server.
• An upload field renders as two parts -- an empty text
field and a Browse button that opens up a local
window explorer on the user's computer. This allows
to quickly browse to the local file and automatically
fills in the file path inside of the text field.
• HTML Upload Field Code:
<form name="myWebForm" action="mailto:your
email@email.com" method="post">
<input type="file" name="uploadField" />
</form>
HTML MAX_FILE_SIZE Code:
<form name="myWebForm" action="mailto:
youremail@email.com" method="post">
<input type="hidden"
name="MAX_FILE_SIZE" value="500" />
<input type="file" name="uploadField" />
</form
html - textareas
An HTML textarea is an oversized Text Field
capable of capturing a message type
information from a user. If you've ever
posted on a forum or left feedback on your
favorite blog, you probably do so using an
HTML textarea.
<textarea name="myTextArea"cols="20" rows="10">Please
limit your response to 100 characters.</textarea><br />
<textarea name="myTextArea" cols="40" rows="2">Please
limit your response to 200 characters.</textarea><br />
<textarea name="myTextArea" cols="45" rows="5">Please
limit your response to 500 characters.</textarea><br />
html - textarea wrap
The wrap attribute refers to how the
user input reacts when it reaches the
end of each row in the text field.
Wrapping can be defined using one of
three values:

1.soft
2.hard
3.off
HTML Text Area Word Wrap Code:
<textarea cols="20" rows="5"
wrap="hard">
As you can see many times word
wrapping is often the desired look
for your textareas. Since it
makes everything nice and easy to
read and preserves line breaks.
</textarea>
html - text areas: readonly
Setting a "yes" or "no" value for the
readonly attribute determines whether
or not a viewer has permission to
manipulate the text inside the text field.

HTML Readonly Attribute:


<textarea cols="20" rows="5" wrap="hard"
readonly="yes">
As you can see many times word wrapping is often the
desired look for your text areas. Since it makes everything
nice and easy to read.
html - text areas: disabled
Disabling the textarea altogether prevents the surfer
from highlighting, copying, or modifying the field in
any way. To accomplish this, set the disabled property
to "yes".

HTML Code:
<textarea cols="20" rows="5" wrap="hard"
disabled="yes">
As you can see many times word wrapping is often the
desired look for your text areas. Since it
makes everything nice and easy to read.
</textarea>
The Submit Button
<input type="submit"> defines a button for submitting a
form to a form-handler. The form-handler is typically a
server page with a script for processing input data. The
form-handler is specified in the form's action attribute:
Example
<form action = "action_page.php">
First name:<br> <input type="text" name="firstname"
value = "Mickey"> <br>
Last name:<br><input type="text" name="lastname"
value="Mouse">
<br><br><input type="submit" value="Submit">
</form>
The Action Attribute
• The action attribute defines the action
to be performed when the form is
submitted.
• The common way to submit a form to a
server, is by using a submit button.
Normally, the form is submitted to a
web page on a web server. In the
example above, a server-side script is
specified to handle the submitted
form:
<form action="action_page.php">
If the action attribute is omitted,
the action is set to the current
page.
The Method Attribute
The method attribute specifies the HTTP
method (GET or POST) to be used when
submitting the forms:

<form action="action_page.php"
method="GET"> OR:

<form action="action_page.php"
method="POST">
When to Use GET?
• You can use GET (the default method): If
the form submission is passive (like a
search engine query), and without
sensitive information.
• When you use GET, the form data will be
visible in the page address:

• action_page.php?
firstname=Mickey&lastname=Mouse
GET is best suited to short amounts of data. Size
limitations are set in your browser.
When to Use POST?
• You should use POST: If the
form is updating data, or
includes sensitive
information (password).
• POST offers better security
because the submitted data
is not visible in the page
address.
<form>
Attribute
attributes:
Description
accept- Specifies the charset used in the submitted form
charset (default: the page charset).
action Specifies an address (url) where to submit the form
(default: the submitting page).
autocomple Specifies if the browser should autocomplete the
te form (default: on).
enctype Specifies the encoding of the submitted data (default:
is url-encoded).
method Specifies the HTTP method used when submitting
the form (default: GET).
name Specifies a name used to identify the form (for
DOM usage: document.forms.name).
novalidate Specifies that the browser should not validate the
form.
target Specifies the target of the address in the action
attribute (default:_self).
The <select> Element (Drop-Down List)
The <select> element defines a drop-down list:

<select name="cars">
<option value="volvo">Volvo</option>
<option value=“hundai">hundai</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
The <button> Element
The <button> element defines a clickable
button:

Example

<button type="button" 'Hello World!')">


Click Me!</button>
HTML5 <datalist> Element
• The <datalist> element specifies a
list of pre-defined options for an
<input> element. Users will see a
drop-down list of pre-defined
options as they input data.
• The list attribute of the <input>
element, must refer to the id
attribute of the <datalist>
element.
<form action="action_page.php">
<input list="browsers">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>
<keygen> Element
The purpose of the <keygen> element is to
provide a secure way to authenticate users.
The <keygen> element specifies a key-pair
generator field in a form. When the form is
submitted, two keys are generated, one
private and one public. The private key is
stored locally, and the public key is sent to
the server. The public key could be used to
generate a client certificate to authenticate
the user in the future.
<output> Element
The <output> element represents the result of a
calculation (like one performed by a script).
<form action="action_page.asp">
Or <form oninput="x.value=parseInt(a.value)
+parseInt(b.value)">
0
<input type="range" id="a"
name="a" value="50"> +
<input type="number" id="b"
name="b" value="50">
=<output name="x" for="a
b"></output>
new in HTML5.
Tag Description
<form> Defines an HTML form for user input
<input> Defines an input control
<textarea> Defines a multiline input control (text area)
<label> Defines a label for an <input> element
<fieldset> Groups related elements in a form
<legend> Defines a caption for a <fieldset> element
<select> Defines a drop-down list
<optgroup> Defines a group of related options in a drop-down
list
<option> Defines an option in a drop-down list
<button> Defines a clickable button
<datalist> Specifies a list of pre-defined options for input
controls
<keygen> Defines a key-pair generator field (for forms)
<output> Defines the result of a calculation
Handling User Input using
PHP
A form handler is a program or script
that processes the information
submitted from a Web form

A form handler performs the following:


–Verifies that the user entered the minimum
amount of data to process the form
–Validates form data
–Works with the submitted data
–Returns appropriate output as a Web page

35
Web forms are interactive controls
that allow users to enter and submit
data to a processing script
A Web form requires attributes in the opening
<form> tag:

Action attribute: Identifies the program on the


Web server that will process the form data
when it is submitted

Method attribute: Specifies how the form data


will be sent to the processing script
36
Adding an action Attribute
The opening form tag requires an action
attribute

The value of the action attribute identifies the


program on the Web server that will process the
form data when the form is submitted
<form
action="http://www.example.com/
HandleFormInput.php">

37
GET vs POST
• The “post” method embeds the form data
in the request message
• The “get” method appends the form
data to the URL specified in the form’s
action attribute
• When a Web form is submitted using the
“post” method, PHP automatically creates
and populates a $_POST array.
• When the “get” method is used, PHP
creates and populates a $_GET
38
array.
Form fields are sent to the Web
server as a name/value pair
–The name portion of the name/value pair
becomes the key of an element in the
$_POST or
$_GET array, depending on which
method was used to submit the data
–The value portion of the name/value pair
is populated by the data that the user
enters in the input control on the Web
form 39
The method Attribute
• When submitting data using the
“get” method, form data is
appended to the URL specified by
the action attribute
• Name/value pairs appended to the
URL are called URL tokens

40
PHP Form Handling
Example
<form action="welcome.php"
method="get">
Name: <input type="text" Welcome
name="names" /> <?php
Age: <input type="text" name="age" /> echo $_GET["names"];
<input type="submit" /> ?>.<br />
</form> You are
<?php
When the user clicks the "Submit"
button, the URL sent to the server could echo $_GET["age"];
look something like this: ?> years old!
http://localhost/welcome.php?
fname=Peter&age=37
The method Attribute
• The form data is separated from
the URL by a question mark (?)
• Individual elements are separated
by an ampersand (&)
• The element name is separated
from the value by an equal sign
(=).
• Spaces in the name and value fields
are encoded as plus signs (+)
42
The method Attribute
All other characters except letters, numbers,
hyphens (-), underscores (_) and periods (.)
are encoded using a percent sign (%)
followed by the two-digit hexadecimal
representation of the character’s ASCII value

http://www.example.net/process_Sc
holarship.
php?
fName=John&lName=Smith&Submit=Sen
d+Form 43
Get method Pros/Cons
• Limitations of the “get” method for submitting
form data
• Restricts the number of characters that
can be appended to a single variable to
100
• The form values are appended to the URL in
plain text, making a URL request insecure

• Advantage (for debugging) of the “get”


method for submitting form data
• Passed values are visible in the Address
Bar of the browser
44
RetrievingThe PHP script that processes the
user- submitted data is called a form handler.
Submitted Data
The values stored in the $_POST array can be
accessed and displayed by the echo statement as
shown below:

$firstName = $_POST['fName’];
$lastName = $_POST['lName’];

echo "Thank you for filling out the


scholarship form,".$firstName."".
$lastName . ".";
45
The $_POST Function
• The built-in $_POST function is used to
collect values from a form sent with
method="post". Welcome
• Information sent from a form with the POST <?php
method is invisible to others and has no echo $_POST["fname"];
limits on the amount of information to ?>
send. .<br /> You are
• Note: However, there is an 8 Mb max size <?php
for the POST method, by default (can be echo $_POST["age"];
changed by setting the post_max_size in ?> years old!
the php.ini file). When the user clicks the
Example "Submit" button, the URL
<form action="welcome.php" will look like this:
method=“post"> http://localhost/welcome.p
Name: <input type="text" name="fname" /> hp
Age: <input type="text" name="age" />
<input type="submit" />
Handling Submitted Form
Data
• It is necessary to validate Web form data to
ensure PHP can use the data

• The optimal way to ensure valid form data is


only allow the user to enter an acceptable
response

• Examples of data validation include


verifying that the user did not leave any
required fields blank
• an e-mail address was entered in the correct
format the user did not exceed the word limit47
in a comment box
Checking Form Variables for
Values
• When form data is posted using the “post” or
“get” method, all controls except unchecked
radio buttons and checkboxes get sent to the
server even if they do not contain data
• The empty() function is used to determine if
a variable contains a value
• The empty() function returns FALSE if the
variable being checked has a nonempty and
nonzero value, and a value of TRUE if the
variable has an empty or zero value
48
Validating Entered Data
• Validating form data refers to verifying
that the value entered in a field is
appropriate for the data type that
should have been entered
• The best way to ensure valid form data is
to build the Web form with controls (such
as check boxes, radio buttons, and
selection lists) that only allow the user to
select valid responses
• Unique information, such as user name,
password, or e- mail must be validated 49
Validating Numeric Data
All data in a Web form is string data and
PHP automatically converts string data to
numeric data if the string is a number
The is_numeric() function is used to
determine if a variable contains a number

The round() function can be used to a


numeric variable with an appropriate
number of decimal places
50
Handling Multiple Errors
• When processing a Web form, it
is best to track any errors on the
form during processing and
then redisplay the form for the
user to correct all the errors at
one time

51
Redisplaying the Web Form
A sticky form is used to redisplay the form with
the controls set to the values the user entered the
last time the form was submitted

The following syntax illustrates how to use the


value attribute to display previous submitted values
in sticky form:
<p>First Name: <input type = “text”
name = “fName” value = “<?php echo
$firstName; ?> /> </p>”

52
Creating an All-in-One Form
• A two-part form has one page
that displays the form and one
page that processes the form data

• For simple forms that require only


minimal processing, it’s often easier
to use an All-in-One form—a single
script used display a Web form and
process its data
53
Validating an All-in-One Form
It uses a conditional to determine if the form
has been submitted or if it is being viewed
for the first time
The isset() function is used to determine if
the $Submit variable has been set
if (isset($Submit)) {
// Validate the data
}
The argument of the isset() function is the name
assigned to the Submit button in the Web form

54
Redisplaying the Web Form
If the submitted data did not pass all validation
checks or no data has been entered, the All-in-One
form will display the Web form, for the user to enter
data for the first time or re-enter data that did not
pass validation
if (isset ($_POST['Submit'])) {
// Process the data
}
else {
// Display the Web form
} 55
DOM (Document Object Model)
• The Document Object Model (DOM)
is a programming interface for
HTML and XML(Extensible markup
language) documents.
• It defines the logical structure of
documents and the way a document
is accessed and manipulated.

56
DOM (Document Object Model)
• DOM is a way to represent the webpage
in the structured hierarchical way so that
it will become easier for programmers
and users to glide through the
document.
• With DOM, we can easily access and
manipulate tags, IDs, classes, Attributes
or Elements using commands or
methods provided by Document object. 57
Structure of DOM
• DOM can be thought of as Tree or
Forest(more than one tree).
• The term structure model is sometimes
used to describe the tree-like
representation of a document.
• If any two DOM implementations are
used to create a representation of the
same document, they will create the
same structure model, with precisely the
same objects and relationships.
58
1.Window Object: Window Object is at
Properties of DOM always at top of hierarchy.
2.Document object: When HTML
document is loaded into a window, it
becomes a document object.
3.Form Object: It is represented by form
tags.
4.Link Objects: It is represented by link
tags.
5.Anchor Objects: It is represented by a
href tags.
6.Form Control Elements:: Form can
have many control elements such as text
fields, buttons, radio buttons, and
checkboxes, etc.

59
Methods of Document Object
• write(“string”): writes the given string on the
document.
• getElementById(): returns the element having
the given id value.
• getElementsByName(): returns all the
elements having the given name value.
• getElementsByTagName(): returns all the
elements having the given tag name.
• getElementsByClassName(): returns all the
elements having the given class name.
60
Example
<Table>
<ROWS>
<TR>
<TD>Car</TD>
<TD>Scooter</TD>
</TR>
<TR>
<TD>MotorBike</TD>
<TD>Bus</TD>
</TR>
</ROWS>
</Table>
61
What DOM is not ?

1. The Document Object Model is not a binary


description where it does not define any binary
source code in its interfaces.
2. The Document Object Model is not used to describe
objects in XML or HTML.
3. The Document Object Model is not represented by
set of data structures; it is an interface which
specifies object representation.
4. The Document Object Model does not show
criticality of objects in documents i.e. it doesn’t have
information about which object in document is
appropriate to the context and which is not. 62
Levels of DOM
• Level 0: Provides low-level set of
interfaces.
• Level 1: DOM level 1 can be described in
two parts: CORE and HTML.
• CORE provides a low-level interfaces
that can be used to represent any
structured document.
• HTML provides high-level interfaces
that can be used to represent HTML
document. 63
Levels of DOM
Level 2 : consists of six specifications: CORE2, VIEWS,
EVENTS, STYLE, TRAVERSAL and RANGE.
CORE2: extends functionality of CORE specified by DOM
level 1.
VIEWS: views allows programs to dynamically access and
manipulate content of document.
EVENTS: Events are scripts that is either executed by
browser when user reacts to web page.
STYLE: allows programs to dynamically access and
manipulate content of style sheets.
TRAVERSAL: allows programs to dynamically traverse
the document.
RANGE: allows programs to dynamically identify a range
of content in document.
64
Levels of DOM
Level 3: consists of five different specifications: CORE3,
LOAD and SAVE, VALIDATION, EVENTS, and XPATH.
CORE3: extends functionality of CORE specified by DOM
level 2.
LOAD and SAVE: allows program to dynamically load the
content of XML document into DOM document and save
the DOM Document into XML document by serialization.
VALIDATION: allows program to dynamically update the
content and structure of document while ensuring
document remains valid.
EVENTS: extends functionality of Events specified by
DOM Level 2.
XPATH: XPATH is a path language that can be used to
access DOM tree. 65

You might also like