Unit III - Form and Event Handling
Unit III - Form and Event Handling
Unit III - Form and Event Handling
3.1 Building blocks of a form, properties and methods of form, Button, Text, Text
area, Checkbox, Radio button, Select element.
HTML Forms are required, when you want to collect some data from the site
visitor. For example, during user registration you would like to collect information such
as name, email address, credit card, etc.
A form will take input from the site visitor and then will post it to a back-end
application such as CGI, ASP Script or PHP script etc. The back-end application will
perform required processing on the passed data based on defined business logic inside
the application.
There are various form elements available like text fields, textarea fields,
drop-down menus, radio buttons, checkboxes etc.
The HTML <form> tag is used to create an HTML form and it has the following syntax −
<form action = "URL" method = "GET|POST">
// form elements like input, textarea etc.
</form>
Form Attributes
Apart from common attributes, following is a list of the most frequently used form
attributes −
Action - Backend script ready to process your passed data.
Method - Method to be used to upload data. The most frequently used are GET and
POST methods.
Target - Specify the target window or frame where the result of the script will be
displayed. It takes values like _blank, _self, _parent etc.
1
Form and Event Handling
2
Form and Event Handling
<html>
<head> <title>Password Input Control</title> </head>
<body>
<form>
User ID : <input type = "text" name = "user_id" /> <br>
Password: <input type = "password" name = "password" />
</form>
</body> </html>
Attributes
Following is the list of attributes for <input> tag for creating password field.
type - Indicates the type of input control and for password input control it will be set to
password.
name - Used to give a name to the control which is sent to the server to be recognized
and get the value.
value - This can be used to provide an initial value inside the control.
size - Allows to specify the width of the text-input control in terms of characters.
maxlength - Allows to specify the maximum number of characters a user can enter into
the text box.
➔ Multiple Line Text Input Controls
This is used when the user is required to give details that may be longer than a single
sentence. Multi-line input controls are created using HTML <textarea> tag.
Example
Here is a basic example of a multi-line text input used to take item description −
<html>
<head> <title>Multiple-Line Input Control</title> </head>
<body>
<form>
Description:<br /><textarea rows = "5" cols = "50" name = "description">
Enter description here...
</textarea>
</form>
</body>
</html>
Attributes
Following is the list of attributes for <textarea> tag.
name - Used to give a name to the control which is sent to the server to be recognized
and get the value.
rows - Indicates the number of rows of text area box.
cols - Indicates the number of columns of text area box
3
Form and Event Handling
➔ Checkbox Control
Checkboxes are used when more than one option is required to be selected. They are
also created using HTML <input> tag but type attribute is set to checkbox..
Example
Here is an example HTML code for a form with two checkboxes −
<html>
<head> <title>Checkbox Control</title> </head>
<body>
<form>
<input type = "checkbox" name = "maths" value = "on"> Maths
<input type = "checkbox" name = "physics" value = "on"> Physics
</form>
</body> </html>
Attributes
Following is the list of attributes for <checkbox> tag.
type - Indicates the type of input control and for checkbox input control it will be set to
checkbox.
name - Used to give a name to the control which is sent to the server to be recognized
and get the value.
value - The value that will be used if the checkbox is selected.
checked - Set to checked if you want to select it by default.
Radio Button Control
Radio buttons are used when out of many options, just one option is required to be
selected. They are also created using HTML <input> tag but type attribute is set to
radio.
Example
Here is an example HTML code for a form with two radio buttons −
<html>
<head> <title>Radio Box Control</title> </head>
<body>
<form>
<input type = "radio" name = "subject" value = "maths"> Maths
<input type = "radio" name = "subject" value = "physics"> Physics
</form>
</body> </html>
Attributes
Following is the list of attributes for radio button.
type - Indicates the type of input control and for checkbox input control it will be set to
radio.
4
Form and Event Handling
name - Used to give a name to the control which is sent to the server to be recognized
and get the value.
value - The value that will be used if the radio box is selected.
checked - Set to checked if you want to select it by default.
➔ Select Box Control
A select box, also called drop down box which provides option to list down various
options in the form of drop down list, from where a user can select one or more options.
Example
Here is an example HTML code for a form with one drop down box
<html>
<head> <title>Select Box Control</title> </head>
<body>
<form>
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
</form>
</body> </html>
Attributes
Following is the list of important attributes of <select> tag −
name - Used to give a name to the control which is sent to the server to be recognized
and get the value.
size - This can be used to present a scrolling list box.
multiple - If set to "multiple" then allows a user to select multiple items from the menu.
Following is the list of important attributes of <option> tag −
value - The value that will be used if an option in the select box box is selected.
selected - Specifies that this option should be the initially selected value when the page
loads.
label - An alternative way of labeling options
➔ File Upload Box
If you want to allow a user to upload a file to your website, you will need to use a file
upload box, also known as a file select box. This is also created using the <input>
element but type attribute is set to file.
Example
Here is an example HTML code for a form with one file upload box −
<html>
<head> <title>File Upload Box</title></head>
<body>
5
Form and Event Handling
<form>
<input type = "file" name = "fileupload" accept = "image/*" />
</form>
</body> </html>
Attributes
Following is the list of important attributes of file upload box −
name - Used to give a name to the control which is sent to the server to be recognized
and get the value.
accept - Specifies the types of files that the server accepts.
➔ Button Controls
There are various ways in HTML to create clickable buttons. You can also create a
clickable button using <input>tag by setting its type attribute to button.
The type attribute can take the following values −
submit - This creates a button that automatically submits a form.
reset - This creates a button that automatically resets form controls to their initial
values.
button - This creates a button that is used to trigger a client-side script when the user
clicks that button.
image - This creates a clickable button but we can use an image as the background of
the button.
Example
Here is an example HTML code for a form with three types of buttons −
<html>
<head> <title>File Upload Box</title> </head>
<body>
<form>
<input type = "submit" name = "submit" value = "Submit" />
<input type = "reset" name = "reset" value = "Reset" />
<input type = "button" name = "ok" value = "OK" />
<input type = "image" name = "imagebutton" src = "/images/img.jpg" />
</form>
</body> </html>
3.2 Form events:
● Mouse Events
Such events which are generated by the mouse are called mouse events. For
example, if a user clicks on an element (div, button etc.), onclick event is generated.
Similarly, if the user moves the mouse's cursor to a web element, onmouseover event is
generated.
6
Form and Event Handling
The mouse is highly used during web surfing. So using mouse events you can
design an interactive webpage.
The list of all mouse events provided in javascript is given below.
1. onclick 4. ondblclick
2. onmouseover 5. onmousedown
3. onmouseout 6. onmouseup
You can use Mouse events with almost all HTML tags. But there are also some
tags with which you cannot use these events. Their list is given below.
➔ onclick
Onclick event is generated when user clicks on an element. When this event is
generated, you can take many actions, such as you can call a function or show an alert.
This is the most common event among the mouse events.
The general syntax of this event is given below.
<element-name onclick="javascript-code"></element-name>
Let us now try to understand this with an example.
<html>
<body> <h1>The onclick Event</h1>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello Friends";
}
</script>
</body></html>
➔ onmouseover
The onmouseover event is generated when the user moves the mouse cursor
over an element. You can take many types of actions when this event is generated. As
soon as the user moves the mouse on a heading, you can show the detail related to
that heading in a div.
This event is mostly used with the onmouseout event. Its general syntax is being given
below.
<element-name onmouseover="java-script code"></element-name>
This event is explained by the following example.
<!– onmouseoverEventDemo.html –>
<html>
<head> <title>onmouseover Demo</title> </head>
<body>
<button onmouseover="document.bgColor='red'">Red</button>
7
Form and Event Handling
<button onmouseover="document.bgColor='green'">Green</button>
<button onmouseover="document.bgColor='blue'">Blue</button>
</body> </html>
➔ onmouseout
Onmouseout event is generated when a user removes the mouse cursor from an
element. This event is mostly used with the onmouseover event. Its general syntax is
being given below.
<element-name onmouseout="javascript-code"></element-name>
This event is explained through the following example.
<html>
<head><title>onmouseout Demo</title></head>
<body>
<button onmouseover = "document.bgColor=’white'" onmouseout =
"document.bgColor = ’black'" > Lights </button>
</body>
</html>
➔ ondblclick
ondblclick event is generated whenever user double clicks on an element. Many actions
can be taken when this event is generated. For example, if the user double clicks on an
image, then the size of that image can be large. Its general syntax is being given below.
<element-name ondblclick="javascript-code"></element-name>
The example of this event is given below.
<html>
<head> <title>ondblclick Demo</title> </head>
<body>
<p ondblclick="myFunction()">Double-click on this Paragraph.</p>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello Friends";
}
</script> </body> </html>
➔ onmousedown
The onmousedown event is generated when the user presses the mouse button on an
element. This event is used with the onmouseup event. Its general syntax is being given
below.
<element-name onmousedown="javascript-code"></element-name>
The example of this event is given below.
8
Form and Event Handling
<html>
<body>
<p id="myP" onmousedown="mouseDown()">
Click mouse left key down on the text! To See the effects
</p>
<script>
function mouseDown() {
document.getElementById("myP").style.color = "red";
}
</script> </body> </html>
➔ onmouseup
The onmouseup event is generated when the user presses and releases the
button from an element. Its general syntax is being given below.
<element-name onmouseup="javascript-code"></element-name>
The example of this event is given below.
<html>
<body>
<p id="myP" onmouseup="mouseUp()">
Click mouse left key down on the text! To See the effects
</p>
<script>
function mouseUp() {
document.getElementById("myP").style.color = "green";
}
</script> </body> </html>
Key Events
Keyboard events are events that are generated when the user interacts with the
keyboard. If you want to handle keyboard actions, then you can use keyboard events for
this.
For example, you can show a message when the key is pressed by the user, you
can change the color of the text, change the background color of the document, or you
can complete any other task.
Javascript provides you with 3 keyboard events.
1. onkeypress–When user presses a key(ctrl, shift, alt are excluded from this event)
2. onkeydown – When user press any key from keyboard
3. onkeyup – When user releases a key after pressing
These events are given in detail below. By understanding and using them properly, you
can make your page even more interactive.
9
Form and Event Handling
➔ onkeypress
The onkeypress event is generated when the user presses a key on the keyboard. If
seen in the context of a webpage, the keyboard is used for inputting text boxes or for
online gaming etc.
Many actions can be taken when this event is generated, such as you can show a
message or initiate a task.
This event is not generated for all keys. There are also some keys such as alt, ctrl and
shift etc. for which this event is not generated. If you just want to see if any keypress
has happened or not, then you can handle the onkeydown event for this.
The example of this event is given below.
<html>
<head> <title>onkeypress Demo</title> <script>
function keypressFunction()
{
document.bgColor="red";
}
</script> </head>
<body>
<form><input type="text" onkeypress="keypressFunction()"></form>
</body> </html>
In the above example, as soon as the user does a keypress, the keypressFunction () is
called and the background color of the document becomes red.
In this example, if you press shift, ctrl and alt key then the event is not generated.
➔ onkeydown
The onkeydown event is generated only when the key is pressed from the user's
keyboard. This event is used with the onkeyup event. This event works like an
onkeypress event but as I told you earlier the onkeypress event is not able to detect all
the keys.
If you want to handle every key press of the keyboard, then for this you will handle
onkeydown event. The example is given below.
<html>
<head> <title>onkeydown</title> <script>
function keydownFunction()
{ document.bgColor = ”green”; }
</script> </head>
<body> <form>
<input type=”text” onkeydown=”keydownFunction()”>
</form>
</body> </html>
10
Form and Event Handling
In the example above, when you press any key on the keyboard, an onkeydown event
is generated which calls keydownFunction () and the background color of the document
turns green.
➔ onkeyup
Onkeyup event is generated when the user releases the key after pressing it. This event
is used with onkeydown. You can handle this event in many ways. Like you can change
the text to uppercase. The example is given below.
<html>
<head> <title>onkeyup Demo</title>
<script>
function keyupFunction(input)
{
input.style.color="red";
}
</script> </head>
<body>
<form>
<input type="text" id="t1" onkeyup="keyupFunction(this)">
</form>
</body> </html>
In the above example, as soon as you release the key, the keyupFunction () is called
and the color of the typed text changes.
11
Form and Event Handling
forms which is accessed by its index value. The first form has index value is 0. Second
form has index value 1 and so on. If the document has no forms, the returned collection
is empty, with a length of zero.
Access the forms element by using elements properties such as “name”, “value” etc
The forms read-only property of the Document interface returns an HTMLCollection
listing all the <form> elements contained in the document.
Syntax:
collection = document.forms;
Value
An HTMLCollection object listing all of the document's forms. Each item in the collection
is a HTMLFormElement representing a single <form> element.
ex. document.forms.form1.username.value
In the above example document.forms gets the HTML Collection of form whereas form1
is the form name and username is the element name of form1. This is get the value
property of username text.
This can be accessed by using index value as:
<form action=”” name=”form1”>
User Name: <input type=”text” value=”User Name” name=”uname”> <br>
<input type=”submit” value=”Click Me” name=”submitbtn”>
</form>
We can access by index of forms and elements:
document.form[0].elements[0].value;
or by using properties of elements
document.forms.form1.uname.value;
We can access properties values of form objects
document.forms.form1.method;
This will gives the method name used for form1 that is : GET which is the default value
of form1
Examples:
<html>
<head> <title>Access element value</title> </head>
<body>
<h1>Welcome User</h1>
<h1 id="msg"></h1>
<form name="form1" action="" method="get">
<input type="text" name="user"> <br>
<input type="submit" name="btnsubmit" onclick="welcome()">
</form>
<script type="text/javascript">
12
Form and Event Handling
function welcome(){
var disp = document.forms[0].elements[0].value;
document.write("Welcome to " + disp);
document.getElementById("msg").innerHTML = "Welcome to " + disp;
}
</script></body></html>
Access form elements value:
<html>
<head>
<title>Form access elements </title>
</head>
<body>
<form action="welcome.html">
Name: <input type="text" name="uname"><br>
Address: <br> <textarea name="addr" id="addr1" cols="29" rows="3"></textarea><br>
<input type="button" value="Ok" name="okbtn" onclick="disp()">
</form>
<script>
function disp(){
with(document.forms[0]){
document.write("Welcome " + elements[0].value + " Address is " + addr.value );
}
}
</script> </body> </html>
Use of this keyword:
<html>
<head>
<title>this keyword use</title>
</head>
<body>
<button class=b1> Submit Button Value 1</button>
<button class=b1> Submit Button Value 2</button>
<button class=b1> Submit Button Value 3</button>
<button class=b1> Submit Button Value 4</button>
<p id="print">Display Values here</p>
<script>
var btn = document.getElementsByClassName("b1");
var disp = document.getElementById("print");
for(var i = 0; i<btn.length; i++){
13
Form and Event Handling
btn[i].onclick = function() {
disp.innerHTML = this.innerHTML;
};
}
</script>
</body> </html>
3.4 Changing attribute value dynamically:
We can change any html form attribute value, styles dynamically by using onchange
event of form.
Program for Changing Attributes style color and background color dynamically:
<html>
<head><title>Change Attribute Style</title></head>
<body>
<form action="">
Name of User: <input type="text" name="uname" onchange="change(this)"><br>
Address of User: <input type="text" name="addr" value="Address"
onchange="change(this)"><br>
<input type="button" name="okbtn" value="Ok">
</form>
<script>
function change(element){
element.style.color = "yellow";
element.style.backgroundColor="red";
}
</script> </body> </html>
14
Form and Event Handling
15
Form and Event Handling
subjects[0].value = 3
}
else if(ev == 2){
subjects[0].text = "DSU";
subjects[0].value = 1
subjects[1].text = "CGR";
subjects[0].value = 2
subjects[2].text = "DBMS";
subjects[0].value = 3
}
else {
subjects[0].text = "OSY";
subjects[0].value = 1
subjects[1].text = "STE";
subjects[0].value = 2
subjects[2].text = "CSS";
subjects[0].value = 3
}
}
}
</script>
</body>
</html>
output:
16
Form and Event Handling
<fieldset>
<legend>Evaluating CheckBox Selection</legend>
<form action="" name="f1">
<input type="checkbox" name="c1" value="c"> C Language <br>
<input type="checkbox" name="c2" value="c++"> C++ Language <br>
<input type="checkbox" name="c3" value="java"> JAVA Language <br>
<input type="checkbox" name="c4" value="dotnet"> DOT NET Language <br>
<input type="checkbox" name="c5" value="js"> JavaScript Language <br>
<h1> <label id="view"></label></h1>
<input type="reset" value="Click Me" onclick="checkme()" >
</form>
</fieldset>
<script>
function checkme(){
with(document.forms.f1){
if(c1.checked == true){
document.getElementById("view").innerHTML = " C Language";
}
else if(c2.checked == true){
document.getElementById("view").innerHTML = " C++ Language";
}
else if(c3.checked == true){
document.getElementById("view").innerHTML = " Java Language";
}
else if(c4.checked == true){
document.getElementById("view").innerHTML = " Dot Net Language";
}
else if(c5.checked == true){
document.getElementById("view").innerHTML = " JavaScript Language";
}
else {
document.getElementById("view").innerHTML = " Please Select Language";
document.getElementById("view").style.color = "Red";
}
}
}
</script>
</body>
</html>
17
Form and Event Handling
output:
18
Form and Event Handling
19
Form and Event Handling
background: aqua;
width: 7%;
padding: 10px; }
#resetbtn {
background: green;
width: 7%;
color: white;
padding: 10px; }
</style>
</head>
<body>
<h2>Student Form</h2>
<form action="" name="form1">
Name <input type="text" name="name"><br>
Roll Number <input type="text" name="rn"><br>
<p id="submitbtn" onclick="javascript:document.forms.form1.submit()">Click Me</p>
<p id="resetbtn"onclick="javascript:document.forms.form1.reset()">Reset Values</p>
</form>
</body>
</html>
Disable Elements
An element can be disabled in HTML by setting disable property to true and enabled
again by setting disabled=false.
<html>
<head><title>Disable Elements</title></head>
<body>
<h2>Disable Elements</h2>
<form action="" name="form1">
Your Name: <input type="text" name="t1"><br>
<input type="button" name="b1" value="Click To Enable" onclick="enable()"><br>
<input type="button" name="b2" value="Click To Disable" onclick="disable()">
</form>
<script>
with(document.forms.form1){
function enable(){
t1.disabled = false;
}
function disable(){
t1.disabled = true;
20
Form and Event Handling
}
}
</script>
</body>
</html>
Read Only Elements
The readOnly property sets or returns whether a text field is read-only, or not.
A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy
the text from it.
<html>
<head><title>Read Only Elements</title></head>
<body>
<h2>Read Only Elements</h2>
<form action="" name="form1">
Your Name: <input type="text" name="t1"><br>
<input type="button" name="b1" value="Click To Read" onclick="read()"><br>
<input type="button" name="b2" value="Click To Write" onclick="enter()">
</form>
<script> function read(){
document.forms.form1.t1.readOnly = true;
}
function enter(){
document.forms.form1.t1.readOnly = false;
}
</script>
</body>
</html>
21