0% found this document useful (0 votes)
27 views66 pages

Unit 3 Forms Event Handling

This document covers client-side scripting focusing on form and event handling using JavaScript. It outlines the structure and properties of HTML forms, various form elements, and methods for handling events and manipulating form data. Additionally, it provides code examples demonstrating how to create and manage forms, including input validation and dynamic changes to form elements.

Uploaded by

pawararya2024
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)
27 views66 pages

Unit 3 Forms Event Handling

This document covers client-side scripting focusing on form and event handling using JavaScript. It outlines the structure and properties of HTML forms, various form elements, and methods for handling events and manipulating form data. Additionally, it provides code examples demonstrating how to create and manage forms, including input validation and dynamic changes to form elements.

Uploaded by

pawararya2024
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

Client-Side Scripting (Semester V)

Unit 3
Form and Event Handling

Marks: 10 (R-2, U-4, A-4)


Course Outcome: Create event-based web forms using javascript.
Unit Outcome:
1. Write JavaScript to design a form to accept input values for the given
problem.
2. Use JavaScript to implement form events to solve the given problems.
3. Develop JavaScript to dynamically assign specified attribute value to
the given form control.
4. Use the given intrinsic functions with specified parameters.

Topics and Sub-topics:


3.1: Building blocks of a Form, properties and methods of form, button,
text, text area, checkbox, radio button, select element.
3.2: Form events - Mouse Events, Key Events
3.3: Form objects and elements
3.4: Changing attribute value dynamically
3.5: Changing option list dynamically
3.6: Evaluating checkbox selection
3.7: Changing a label dynamically
3.8: Manipulating form elements
3.9 Intrinsic JavaScript functions, disabling elements, read only elements

Forms are one of the most common web page elements used with JavaScript.
JavaScript form is commonly used with following two reasons:

1
Client-Side Scripting (Semester V)

 To add functionality that makes forms easier for users to fill out
 To validate or process the data that a user enters before t3hat
data is submitted to a server-side script.
JavaScript form object represents HTML form. HTML forms are a very powerful
tool for interacting with users.
An HTML form is used to collect user input. The user input can then be sent to
a server for processing. JavaScript’s interaction with HTML is handled through
events that occur when the user or the browser manipulates a page.

3.1: Building blocks of a Form, properties and methods of form, button,


text, text area, checkbox, radio button, select element:
A form is a section of an HTML document that contains elements such as
radio buttons, text boxes and option lists. HTML form elements are also
known as controls.
Elements are used as an efficient way for a user to enter information into
a form. Typical form control objects also called “widgets” includes the
following:
 Text box for entering a line of text.
 Push button for selecting an action.
 Radio buttons for making one selection among a group of options.
 Check boxes for selecting or deselecting a single, independent
option.

The <form> element can contain one or more of the following form elements:

 <input>
 <textarea>
 <button>
 <select>
 <option>
 <fieldset>
 <label>
 <legend>

The attributes of the form are:

Attribute Value Description


action URL Specifies where to send the form-data when a form is

2
Client-Side Scripting (Semester V)

submitted
method get Specifies the HTTP method to use when sending form-
post data
name text Specifies the name of a form
id Any id Unique identifier
onSubmit Function Event fired up when the form is submitted and before the
name execution of the action.

Syntax:

<form name = “myform” id = “myform” action = “[Link]” onSubmit =


“test()”>
-----objects----
</form>

HTML Form Elements:

Sr HTML Element Type Event Description and


. Property Handle Events
N r
o
1 <input type = “button” onclick A push buttons.
“button”>
or
<button type =
“button”>
2 <input type = “checkbo onchang A toggle button without
“checkbox”> x” e radio button behavior.
3 <input type = “file” onchang An input held for
“file”> e entering the name of a
file to upload to the web
server, value property is
read only.
4 <input type = “hidden” none Data submitted with the
“hidden” form but not visible to
the user.
5 <option> none none A single item within a
select object, event
handlers are 2an the
select object and
no000000000t on
individual option objects.

3
Client-Side Scripting (Semester V)

6 <input type = “passwor onchang An input field for


“password”> d” e password entry where
typed characters are not
visible.
7 <input type = “radio” onchang A toggle button with
“radio”> e radio button behavior
where only one item is
selected at a time.
8 <input type = “reset” onclick A push button that
“reset”> resets a form.
or
<button type =
“reset”>
9 <select> “select- onchang A list or drop-down menu
one” e from which one item
may be selected.
10 <select multiple> “select- onchang A list from which
multiple” e multiple items are
selected.
11 <input type = “submit” onclick A push button that
“submit”> submits a form.
or
<button type =
“submit”>
12 <input type = “text” onchang A single line text entry
“text”> e field.
13 <textarea> “textarea onchang A multi-line text entry
” e field.
14 <label> defines a label

15 <fieldset> tag is used to group


related elements in a
form.
tag draws a box around
the related elements.

<input> tag with its parameters:

1. name: Can be used so that the value of the element can be processed.
2. type: Can be used to specify the type of input.
3. id: Identification name of element.

4
Client-Side Scripting (Semester V)

4. value: Can be used to specify the initial value. It is required when type is
set to checkbox or radio. It should not be used when type is set to file.
5. checked: Can be used when type is set to checkbox or radio to set the
initial state of a checkbox or radio button to be selected.
6. maxlength: Can be used to specify the maximum number of characters
allowed in a textbox.
7. src: Can be used when type is set to image to specify the location of an
image file.
8. alt: Can be used when type is set to image to specify the alternative
text of the image, which should be a short description.

Code: To accept first name, last name, email and birthdate. After clicking on
button, details will be displayed as an output.

<html>
<head>
<style>
fieldset
{
background-color: pink;
}

legend
{
background-color: gray;
color: white;
padding: 5px 10px;
}

input
{
margin: 5px;
}
</style>
</head>
<body>
<form action=" ">
<fieldset>
<legend>Personalia:</legend>

5
Client-Side Scripting (Semester V)

<label for="fname">First name:</label>


<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<label for="birthday">Birthday:</label>
<input type="date" id="birthday" name="birthday"><br><br>
</fieldset>
</form>
<p>Click the button to get the details:</p>
<button onclick="myFunction()">Details</button>
<BR>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
function myFunction()
{
var y = [Link]("fname").value;
[Link]("demo").innerHTML = y;
var x = [Link]("lname").value;
[Link]("demo1").innerHTML = x;
var z = [Link]("email").value;
[Link]("demo2").innerHTML = z;
var w = [Link]("birthday").value;
[Link]("demo3").innerHTML = w;
}
</script>
</body>
</html>
Output:

6
Client-Side Scripting (Semester V)

Properties and Methods:


• The Form object represents a <form> element in an HTML document.
The elements property is an HTML collection that provides convenient
access to all elements of the form. The submit () and reset () methods
allow a form to be submitted or reset under program control.
• Each form in a document is represented as an element of the
[Link][] array. The elements of a form are collected in the
array like object [Link].

Properties of Form:
Sr. Properties Description
No.
1 action Read/Write string that reflects the action attribute of the
form.
2 elements[ An array containing all of the elements of the form. Use it
] to loop through form easily.

7
Client-Side Scripting (Semester V)

3 encoding Read/Write string that specifies how the form data is


encoded.
4 length The number of elements in the form.
5 method Read/Write string that specifies how the method the form
is submitted.
6 name The name of the form.
7 target The name of the target frame or window form is to be
submitted to.

Methods of Form:
Sr. Methods Description
No.
1 reset() Resets the form
2 submit() Submits a form

Methods of Events:
Sr. Methods Description
No.
1 onReset Code is executed when the form is reset.
2 onSubmi Code is executed when form is submitted.
t

Code: Assign values to the text boxes after clicking on a button.

<html> <head>
<script type="text/javascript">
function assign()
{
[Link]="CSS_book";
[Link]="Manisha Padwal";
}
</script>
</head>
<body>
<form id="book">
Title of Book:<input id="title"> <br> <br>
Author of Book:<input id="author"> <br> <br>
<input type="button" id="btn" value="Assign Values" onclick="assign()">
</form>
</body>

8
Client-Side Scripting (Semester V)

</html>
Output:

Forms and the elements they contain can be selected from a document
using
1. getElementById() method
2. getElementsByName() method
3. getElementsByTagName() method
4. getElementsByClassName() method
5. innerHTML property
6. innerText property

getElementById() method :

 The getElementById() method returns the element that has the ID


attribute with the specified value.
 This method is one of the most common methods in the HTML DOM,
and is used almost every time you want to manipulate, or get info from,
an element on your document.

Syntax:

[Link](elementID);

Code: Following code displays after clicking on button, text color is changed
as red.

<html>
<body>

9
Client-Side Scripting (Semester V)

<p id="demo">Click the button to change the color of this


paragraph.</p>

<button onclick="myFunction()">change color</button>

<script>textarea
function myFunction()
{
var x = [Link]("demo");
[Link] = "red";
}
</script>
</body>
</html>
Output:

2. getElementsByName() method
The getElementsByName() method returns a collection of all elements in the
document with the specified name (the value of the name attribute).

Syntax:

[Link](name);
Code: Check all <input> elements with type="checkbox" in the document
that have a name attribute with the value "animal":

<html>

10
Client-Side Scripting (Semester V)

<body>
<input name="program" type="checkbox" value="IF">
Information Technology <br>
<input name="program" type="checkbox" value="CO">
Computer Engineering
<br>
<p>Click the button to check all checkboxes that have a name attribute
with the value "program".</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var x = [Link]("program");
var i;
for (i = 0; i < [Link]; i++)
{
if (x[i].type == "checkbox")
{
x[i].checked = true;
}
}
}
</script>
</body>
</html>
Output:

11
Client-Side Scripting (Semester V)

3. getElementsByTagName() method

The getElementsByTagName() method returns a collection of all


elements in the document with the specified tag name.

Syntax:

[Link](tagname);

Code: Following code illustrates the use of getElementsByTagName() to count


how many LI elements are present in unordered list.
Find out how many <li> elements there are in the document.

<html>
<body>
<p>An unordered list:</p>
<ul>
<li>Information Technology</li>
<li>Computer Engineering</li>
<li>Chemical Engineering</li>
</ul>
<p>Click the button to find out how many li elements there are in this
document. </p>
<button onclick="myFunction()">Click</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x = [Link]("LI");
[Link]("demo").innerHTML = [Link];
}
</script>
</body>
</html>

Output:

12
Client-Side Scripting (Semester V)

Code: Change the background color of all <p> elements in the document as
pink and text color as blue.

<html>
<body>
<p>Computer Engineering</p>
<p>Information Technology</p>
<p>Electronics and Telecommunication</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var x = [Link]("P");
var i;
for (i = 0; i < [Link]; i++) {
x[i].[Link] = "pink";
x[i].[Link] = "blue";
}
}
</script> </body> </html>
Output:

13
Client-Side Scripting (Semester V)

Click on “Try it”

4) getElementsByClassName() Method
The getElementsByClassName() method returns an object
containing all the elements with the specified class names in the
document as objects. Each element in the returned object can be
accessed by its index. This method can be called upon any individual
element to search for its descendant elements with the specified class
names.
Syntax:
[Link](classnames);
Parameters: This method takes only one parameter, which is a string
containing space-separated class names of the elements to search for.

Example:

<!DOCTYPE html>
<html>
<head>
<title>DOM getElementByClassName() Method</title>
<style>
h1 {
color: green;
}
body {
text-align: center;

14
Client-Side Scripting (Semester V)

}
.example {
padding: 10px;
margin: auto;
margin-top: 10px;
border: 1px solid black;
width: 300px;
}
</style>
</head>

<body>
<h1>Client_side Scripting</h1>
<h2>DOM getElementByClassName() Method</h2>
<div>
<h4 class="example">div1</h4>
<h4 class="yellowBorder example">div2</h4>
<h4 class="greenBorder example">div3</h4>
<h4 class="example">div4</h4>
</div>
<script>
[Link]('greenBorder example')[0]
.[Link]="10px solid green";
[Link]('yellowBorder example')[0]
.[Link]="10px solid yellow";
</script>
</body>
</html>
Output:

15
Client-Side Scripting (Semester V)

5) innerHTML property

The easiest way to modify the content of an HTML element is by using


the innerHTML property.

To change the content of an HTML element, use this syntax:

[Link](id).innerHTML = new HTML;

Code: to change the text by using innerHTML property.

<html>
<body>
<script type="text/javascript">
function changeText()
{
[Link]('js').innerHTML = 'Fifth Semester
Javascript!!!!';
}
</script>
<p>Welcome to <b id='js'>JAVASCRIPT</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
</body>
</html>
Output:

16
Client-Side Scripting (Semester V)

Code: Script for count the number of <p> tag and <H2> tag.

<html>
<head>
<style>
div
{
border: 1px solid black;
margin: 5px;
}
</style>
</head>
<body>
<div id="myDIV">
<p>Information Technology</p>
<p>Computer Engg.</p>
<p>Electronics and Telecommunication</p>
<p>Chemical Engg.</p>
</div>
<div id="myh">
<H2>Vidyalankar Polytechnic</H2>
<H2>Vidyalankar Institute of Technology </H2>
</div>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<p id="demo1"></p>
<script>
function myFunction()
{
var x =
[Link]("myDIV").getElementsByTagName("P");
[Link]("demo").innerHTML = [Link];
var y =
[Link]("myh").getElementsByTagName("H2");

17
Client-Side Scripting (Semester V)

[Link]("demo1").innerHTML = [Link];
}
</script>
</body>
</html>
Output:

Code:

<script type="text/javascript">
function changeText()
{
var userInput = [Link]('userInput').value;
[Link]('vp').innerHTML = userInput;
}
</script>
<p>Welcome <b id='vp'>JavaScript</b> </p>
<input type='text' id='userInput' value='Enter Text Here' />
<input type='button' onclick='changeText()' value='Change Text'/>
Output:

Code:

18
Client-Side Scripting (Semester V)

<html>
<body>
Name: <input type="text" id="userInputName" value=""> <br> <br>
Password: <input type="password" id="userInputPwd" value=""> <br>
<br>
<input type="button" onclick="changeText()" value="Change Text">
<p>Name is <b id="vp">JavaScript</b> </p>
<p>Password is <b id="vp1">JavaScript</b> </p>
<script>
function changeText()
{
var userInputName = [Link]("userInputName").value;
[Link]("vp").innerHTML = userInputName;
var userInputPwd = [Link]("userInputPwd").value;
[Link]("vp1").innerHTML = userInputPwd;
}
</script>
</body>
</html>
Output:

Code: Execute a JavaScript when a form is submitted.

<html>
<body>
<p>When you submit the form, a function is triggered which alerts some
text.</p>
<form action="" onsubmit="myFunction()">
Enter name: <input type="text" name="fname">

19
Client-Side Scripting (Semester V)

<input type="submit" value="Submit">


</form>
<script>
function myFunction()
{
alert("The form was submitted");
}
</script>
</body>
</html>
Output:

<input> Element of form:


<input> tag defines the start of an input field where the user can enter data.
Syntax:
<input type="value">

6) innerText property

The innerText property can be used to write the dynamic text on the html
document. Here, text will not be interpreted as html text but a normal text.

It is used mostly in the web pages to generate the dynamic content such as
writing the validation message, password strength etc.

In this example, we are going to display the password strength when releases
the key after press.

<script type="text/javascript" >


function validate() {
var msg;
if([Link]>5){
msg="good";
}

20
Client-Side Scripting (Semester V)

else{
msg="poor";
}
[Link]('mylocation').innerText=msg;
}

</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>

Attributes of <input> Tag:


Name: Name assigns a name to the input field. The name of the input field is
used to send the information to the server.
Value: This attribute sets the value for the input field.
Type: type attributes indicates the type of input element that has to be given
in following table.
Value Description
button Defines a clickable button (mostly used with a JavaScript
to activate a script)
checkbox Defines a checkbox
color Defines a color picker
date Defines a date control (year, month, day (no time))
email Defines a field for an e-mail address
hidden Defines a hidden input field
image Defines an image as the submit button
password Defines a password field
radio Defines a radio button
reset Defines a reset button
submit Defines a submit button
text Default. Defines a single-line text field

Button
:
Button is created by using following code:
<form method = “GET” action = “”>
<input type = “button” name = “MyButton” value = “Click” onclick =
“msg()”>

21
Client-Side Scripting (Semester V)

<form>
There are several types of button, which are specified by the type attribute:
1. Button which corresponds to the graphic component.
2. Submit, which is associated to the form and which starts the loading of
the file assigned to the action attribute.
3. Image button in which an image loaded from a file.
A Button object also represents an HTML <button> element which is specified
as follows:
<button name = “btn” value = “MyButton” onclick = “msg()”>
Inside a <button> element you can put content, like text or images. But this
is not the case with the buttons created with <input> tag.
Attribute Value Description
name name Specifies a name for the button
type button Specifies the type of button
reset
submit
value text Specifies an initial value for the button

Event handling with Button:


A push button that activates a JavaScript when it is clicked:
Syntax:
<input type="button" value=”aaa” onclick=”function_name()”>

OR
<button onclick="Function_name()"> Click me </button>
Code:

<html>
<body>
<h2>Show a Push Button</h2>
<p>The button below activates a JavaScript when it is clicked. </p>
<form>
<input type="button" value="Click me" onclick="msg()">
</form>
<script>
function msg()

22
Client-Side Scripting (Semester V)

{
alert("Hello world!");
}
</script>
</body>
</html>

Output:

Code:

<html>
<body>
<h3>The onclick Event using Button tag. </h3>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction()
{
[Link]("demo").innerHTML = "Welcome to
JavaScript";
}
</script>
</body>
</html>
Output:

23
Client-Side Scripting (Semester V)

Code:

<html>
<body>
<p id="demo">Click me.</p>
<script>
[Link]("demo").onclick = function()
{
myFunction()
};
function myFunction()
{
[Link]("demo").innerHTML = "YOU CLICKED ME!";
}
</script>
</body>
</html>

Output:

Text:

Input “text” is an object to enter a single line of text whose content will be
part of form data.
In html a text is created by following code:
<input type=”text” name=”textname” id=”textid” value=” assign_value” />
Code:

<script type="text/javascript">
function changeText()

24
Client-Side Scripting (Semester V)

{
var userInput = [Link]('userInput').value;
[Link]('vp').innerHTML = userInput;
}
</script>

<input type='text' id='userInput' value='Enter Text Here' />


<p>Welcome <b id='vp'>JavaScript</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
</script>
Output:

TextArea

The Textarea object represents an HTML <textarea> element.


The <textarea> tag indicates a form field where the user can enter a large
amount of text.
You can access a <textarea> element by using getElementById():
Attributes of TextArea tag:
Property Description
cols Sets or returns the value of the cols attribute of a text area
name Sets or returns the value of the name attribute of a text area
rows Sets or returns the value of the rows attribute of a text area
value Sets or returns the contents of a text area
wrap Sets or returns the value of the wrap attribute of a text area.
• Soft: “Soft" forces the words to wrap once inside the
textarea but once the form is submitted, the words will
no longer appear as such, and line breaks and spacing
are not maintained.
• Hard :"Hard" wraps the words inside the text box and
places line breaks at the end of each line so that when
the form is submitted the text will transfer as it appears
in the field, including line breaks and spacing.

25
Client-Side Scripting (Semester V)

[Link] = soft/hard
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.
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".
Code: to demonstrate the <textarea> and its attributes.

<html>
<body>

<textarea cols="30" rows="5" wrap="hard" readonly="yes"


disabled="yes">
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>
</body>

</html>
Output:

In above code, disabled="yes" that is textarea is disabled (cannot perform


any highlighting, copying, or modifying) .
Without using “disabled” attribute of <textarea>

<textarea cols="30" rows="5" wrap="hard" readonly="yes">


Output will be like:

Code: to display the content from textarea.

26
Client-Side Scripting (Semester V)

<html>
<body>
Address:<br>
<textarea id="myTextarea" cols=32 Rows=5>
</textarea>
<p>Click the button to get the content of the text area.</p>
<button type="button" onclick="myFunction()">Display
Address</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x = [Link]("myTextarea").value;
[Link]("demo").innerHTML = x;
}
</script>
</body>
</html>
Output:

Methods of TextArea:
Method Description
select() Selects the entire contents of a text area

Code: Select the contents of a text area.

0
Output:

27
Client-Side Scripting (Semester V)

Checkbox:
<input> elements of type checkbox are rendered by default as boxes that
are checked (ticked) when activated. A checkbox allows you to select single
values for submission in a form (or not).
Syntax for creating checkbox is:
<input type="checkbox" id="myCheck" onclick="myFunction()">
A checkbox can have only two states:
1. Checked
2. Unchecked
Code:

<html>
<body>
<div>
Program:
<br>
<input type="checkbox" name="program" id="it" value="IT">
<label for="it">Information Tech</label> <br>

<input type="checkbox" name="program" id="co" value="CO"


checked>
<label for="co">Computer Engg</label> <br>

<input type="checkbox" name="program" id="ej" value="EJ">


<label for="ej">Electronics</label> <br>
<button onclick="validate();">Validate</button>

28
Client-Side Scripting (Semester V)

</div>

<div id="status">
</div>
<script>
function validate()
{
var elements = [Link]("program");
var statusText = " ";
for (var index=0;index < [Link];index++)
{
statusText = statusText +
elements[index].value+"="+elements[index].checked+"<br>";
}
[Link]("status").innerHTML = statusText;
}
</script>
</body>
</html>

Output:

Radio Button:

The radio button allows the user to choose one of a predefined set of options.
You can define groups with the name property of the radio buttons.

29
Client-Side Scripting (Semester V)

Radio buttons with the same name belong to the same group. Radio buttons
with different names belongs to the different groups. At most one radio
button can be checked in a group.
Syntax:
<input type="radio" id="male" name="gender" value="male">

Code:

<html>
<body>
<form method="post" action=" " onsubmit="return ValidateForm();">
<fieldset>
<legend>Select Course:</legend>
<input type="radio" name="br" value="IT" checked>IT<br>
<input type="radio" name="br" value="CO">CO<br>
<input type="radio" name="br" value="EJ">EJ<br>
<br>
<input type="submit" value="Submit now">
</fieldset>
</form>
<script type="text/javascript">
function ValidateForm()
{
var obj = [Link]("br");
for(var i = 0; i < [Link]; i++)
{
if(obj[i].checked == true)
{
if(confirm("You have selected " + obj[i].value))
return true;
else
return false;
}
}
}
</script>
</body>

30
Client-Side Scripting (Semester V)

</html>

Output:

Select:

Form SELECT elements (<select>) within your form can be accessed and
manipulated in JavaScript via the corresponding Select object.
To access a SELECT element in JavaScript, use the syntax:
[Link] //where myform and selectname are names of
your form/element.
[Link][i] //where i is the position of the select element
within form

[Link]("selectid") //where "selectid" is the ID of the


SELECT element on the page.
Option Object

The Option object represents an HTML <option> element.

Access an Option Object

You can access an <option> element by using getElementById().

Option Object Properties

Property Description

31
Client-Side Scripting (Semester V)

defaultSelect Returns the default value of the selected attribute


ed

disabled Sets or returns whether an option is disabled, or not

form Returns a reference to the form that contains the option

index Sets or returns the index position of an option in a drop-


down list

label Sets or returns the value of the label attribute of an option in


a drop-down list

selected Sets or returns the selected state of an option

text Sets or returns the text of an option

value Sets or returns the value of an option to be sent to the


server

Code: Disable the third option (index 2) in a drop-down list and apply color as
red to disabled index.

<html>
<body>
<select id="programs" size="5">
<option>Computer Engineering</option>
<option>Information Technology</option>
<option>Chemical Engineering</option>
<option>Electronics & TeleComm.</option>
</select>

32
Client-Side Scripting (Semester V)

<p>Click the button to disable the third option (index 2) in the dropdown
list.</p>

<button onclick="myFunction()">Disable Option</button>

<script>
function myFunction()
{
var x = [Link]("programs").options[2].disabled =
true;
[Link]("programs").options[2].[Link] = "red";
}
</script>
</body>
</html>

Output:

Code: Display index and text associated with that index.

<html>
<body>
Select a Program and click the button:
<select id="mySelect">
<option>Information Technology</option>
<option>Computer Engg</option>

33
Client-Side Scripting (Semester V)

<option>Civil Engg</option>
<option>Electronics and Telecommunication</option>
</select>
<button type="button" onclick="myFunction()">
Display index</button>
<script>
function myFunction()
{
var x = [Link]("mySelect").selectedIndex;
var y = [Link]("mySelect").options;
alert("Index: " + y[x].index + " is " + y[x].text);
}
</script>
</body>
</html>

Output:

3. 2 Form Events:

The form property within the document object contains an array of all forms
defined within the document.

34
Client-Side Scripting (Semester V)

Each element within the array is a form object, the index number associated
with the form object defines the order in which the form appears on the
webpage.

The change in the state of an object is known as an Event. In html, there are
various events which represents that some activity is performed by the user
or by the browser. When javascript code is included in HTML, javascript react
over these events and allow the execution. This process of reacting over the
events is called Event Handling. Thus, javascript handles the HTML events
via Event Handlers.

For example, when a user clicks over the browser, add javascript code, which
will execute the task to be performed on the event.

Table: Event handlers for Form Elements.

Object Event Handler

button onClick, onBlur, onFocus

onClick, onBlur,
checkbox
onFocus.

FileUpLoad onClick, onBlur, onFocus

hidden none

onBlur, onFocus,
password
onSelect.

radio onClick, onBlur, onFocus

reset onReset

onFocus, onBlur,
select
onChange.

submit onSubmit

onClick, onBlur, onFocus


text
, onChange

onClick, onBlur, onFocus


textarea
, onChange

35
Client-Side Scripting (Semester V)

The main utility of a button object is to trigger an event, say


an onClick() event, but a button object has no default action.

The are several types of buttons associated with a form:

 submit
 reset
 button

These events are fired when some click related activity is registered.

Form events:

Event Event Description


Performe Handler
d

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form element (The
onblur event occurs when an object loses focus.)

change onchange When the user modifies or changes the value of a


form element
Code: onfocus event

<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
function focusevent()
{
[Link]("input1").[Link]=" green";
}
</script>
</body>
</html>

36
Client-Side Scripting (Semester V)

Output:

Code: onsubmit event

<html>
<body>

<p>When you submit the form, a function is triggered which alerts some
text.</p>

<form action="" onsubmit="myFunction()">


Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

<script>
function myFunction()
{
alert("The form was submitted");
}
</script>
</body>
</html>
Output:

Code: onblur event


Execute a JavaScript when a user leaves an input field, as soon as user leaves
the input field, content in text box is appeared as in uppercase and color is
blue.

37
Client-Side Scripting (Semester V)

<html>
<body>

Enter your name: <input type="text" id="fname" onblur="myFunction()">

<p>When you leave the input field, a function is triggered which


transforms the input text to upper case.</p>

<script>
function myFunction()
{
var x = [Link]("fname");
[Link] = [Link]();
[Link]("fname").[Link]="blue";
}
</script>
</body>
</html>
Output:

Window/Document events:

Event Event Description


Performed Handler

load onload When the browser finishes the loading of the


page

unload onunload When the visitor leaves the current webpage,


the browser unloads it

resize onresize When the visitor resizes the window of the


browser

Code: onload event

38
Client-Side Scripting (Semester V)

<html>
<head>
<script type="text/javascript">
function message() {
alert("Welcome to this page:onload event");
}
</script>
</head>
<body onload="message()">
When page loaded alert is displayed.
</body>
</html>
Output:

Code: onresize event

<html>
<body onresize="myFunction()">

<p>Try to resize the browser window to display the windows height and
width.</p>

<p id="demo"></p>

<script>
function myFunction()
{
var w = [Link];
var h = [Link];
var txt = "Window size: width=" + w + ", height=" + h;

39
Client-Side Scripting (Semester V)

[Link]("demo").innerHTML = txt;
}
</script>
</body>
</html>

Output:

Code: onclick event

d
Output:

Mouse Events:
Attribute Value Description
onclick script Fires on a mouse click on the element
ondblclick script Fires on a mouse double-click on the element
onmousedow script Fires when a mouse button is pressed down on an

40
Client-Side Scripting (Semester V)

n element
onmousemov script Fires when the mouse pointer is moving while it is
e over an element
onmouseout script Fires when the mouse pointer moves out of an
element
onmouseover script Fires when the mouse pointer moves over an
element
onmouseup script Fires when a mouse button is released over an
element
onwheel script Fires when the mouse wheel rolls up or down over
an element
oncontextme script oncontextmenu event occurs when the user right-
nu clicks on an element to open the context menu.

Code: onmouseout and onmouseover event

<html>
<html>
<body>
<img onmouseover="bigImg(this)" onmouseout="normalImg(this)"
border="1" src="[Link]" width="64" height="64">
<script>
function bigImg(x)
{
[Link] ="120px";
[Link] ="120px";
}
function normalImg(x)
{
[Link] = "64px";
[Link] = "64px";
}
</script>
</body> </html>
Output:

41
Client-Side Scripting (Semester V)

Code: onwheel event


When you roll the mouse over the paragraph either up or down, paragraph
text will be increased to 35 pixels.

<html>
<body>

<div id="aa" onwheel="myFunction()">


This example demonstrates how to assign an "onwheel" event event to a
DIV element. Roll the mouse wheel over me - either up or down!</div>

<script>
function myFunction()
{
[Link]("aa").[Link] = "35px";
}
</script>
</body>
</html>
Output:

Code: ondblclick event

<html>
<body>
<h2>

42
Client-Side Scripting (Semester V)

<p id="demo" ondblclick="color_change()">Double-click me to change


my text color.</p> </h2>

<script>
function color_change()
{
[Link]("demo").[Link] = "red";
[Link]("demo").[Link] = "yellow";
}
</script>

</body>
</html>
Output:

Code: onmousedown and onmouseup event

<html>
<body>

<p id="p1" onmousedown="mouseDown()" onmouseup="mouseUp()">


Click the text! The mouseDown() function is triggered when the mouse
button is pressed down over this paragraph. The function sets the color of
the text to red. The mouseUp() function is triggered when the mouse
button is released. The mouseUp() function sets the color of the text to
blue.
</p>
<script>
function mouseDown()
{
[Link]("p1").[Link] = "red";
}
function mouseUp()
{
[Link]("p1").[Link] = "blue";

43
Client-Side Scripting (Semester V)

}
</script>
</body>
</html>
Output:

Code: oncontextmenu event


Execute a JavaScript when the user right-clicks on a <div> element with a
context menu:

<html>
<head>
<style>
div {
background: yellow;
border: 1px solid black;
padding: 10px;
}
</style>
</head>
<body>
<div oncontextmenu="myFunction()" contextmenu="mymenu">
<p>Right-click inside this box to see the context menu!
</div>
<script>
function myFunction()
{
alert("You right-clicked inside the div!");
}

44
Client-Side Scripting (Semester V)

</script>
</body>
</html>
Output:

Code: onmousemove event


Execute a JavaScript when moving the mouse pointer over a <div> element
and display the x and y coordinates.

<html>
<head>
<style>
div {
width: 200px;
height: 100px;
border: 1px solid black;
}
</style>
</head>
<body>
<p>This example demonstrates how to assign an "onmousemove" event
to a div element.</p>
<div onmousemove="myFunction(event)"></div>
<p>Mouse over the rectangle above, and get the coordinates of your
mouse pointer.</p>
<p id="demo"></p>
<script>

45
Client-Side Scripting (Semester V)

function myFunction(e)
{
var x = [Link];
var y = [Link];
var coor = "Coordinates: (" + x + "," + y + ")";
[Link]("demo").innerHTML = coor;
}
</script>
</body>
</html>

Output:

<!DOCTYPE HTML>
<html>
<head>
<title>Example: Working with Mouse events</title>
<style>
body{font-family:Verdana;
background:#44c767; color:#fff;}
</style>
<script>

46
Client-Side Scripting (Semester V)

var count = 0;
function tracker(){
count++;
alert(count + " Mouse moves have been registered");
}
function popup1() {
alert("Event Registered : onMouseOver");
}
function popup2() {
alert("Event Registered : onMouseOut");
}
</script>
</head>
<body>
<p>Move the mouse over the link to trigger the event
<a href="#" onmouseover="popup1()"> onMouseOver</a></p>

<p>Move the mouse over the link to trigger the event


<a href="#" onmouseout="popup2()"> onMouseOver</a></p>

<p>Move the mouse over the button, it keeps a track of number


of times the mouse moves over the button</p>
<button onmouseover="tracker()">Move over this button </button>
</body>
</html>

______________-

47
Client-Side Scripting (Semester V)

<!DOCTYPE HTML>
<html>
<head><title>Javascript Events: Attach an Event Listener</title>
</head>
<body>
<p id="content">We must let go of the life we have planned,
so as to accept the one that is waiting for us </p>
</body>
<script>
var p = [Link]("content");

[Link]('click',change); //event Listener attached


// false denotes that bubbling method of event propogation
function change(){
[Link] ="#FA8B7C";
[Link] ="Verdana";
[Link] ="10px";
[Link] ="#fff";
[Link] ="4px dotted green";
}
</script>
</html>

[Link]
KeyEvent:

These event types belong to the KeyboardEvent Object:

Event Description

48
Client-Side Scripting (Semester V)

keydown The event occurs when the user is pressing a key

keypress The event occurs when the user presses a key

keyup The event occurs when the user releases a key

1) The onkeydown event occurs when the user is pressing a key (on the
keyboard).

Syntax: <element onkeydown="myScript”>

The keydown event occurs when the user presses down a key on the
keyboard. You can handle the keydown event with the onkeydown event
handler. The following example will show you an alert message when the
keydown event occurs.

Code: onkeydown event

<html>
<body>
<input type="text" onkeydown="alert('You have pressed a key inside
text input!')">
<hr>
<textarea cols="30" onkeydown="alert('You have pressed a key inside
textarea!')"></textarea>
<p><strong>Note:</strong> Try to enter some text inside input box and
textarea.</p>
</body>
</html>
Output:

49
Client-Side Scripting (Semester V)

2) The onkeyup event occurs when the user releases a key (on the
keyboard).
Syntax: <element onkeyup="myScript">
You can handle the keyup event with the onkeyup event handler.
The following example will show you an alert message when the keyup event
occurs.
Code: onkeyup event

<html>
<body>
<input type="text" onkeyup="alert('You have released a key inside text
input!')">
<hr>
<textarea cols="30" onkeyup="alert('You have released a key inside
textarea!')"></textarea>
<p><strong>Note:</strong> Try to enter some text inside input box and
textarea.</p>
</body>
</html>
Output:

3) The onkeypress event occurs when the user presses a key (on the
keyboard).
Syntax: <element onkeypress="myScript">
The keypress event occurs when a user presses down a key on the keyboard
that has a character value associated with it. For example, keys like Ctrl,

50
Client-Side Scripting (Semester V)

Shift, Alt, Esc, Arrow keys, etc. will not generate a keypress event, but will
generate a keydown and keyup event.
You can handle the keypress event with the onkeypress event handler.
The following example will show you an alert message when the keypress
event occurs.
Code: onkeypress event

<html>
<body>
<p>Press a key inside the text field to set a red background color.</p>

<input type="text" id="demo" onkeypress="myFunction()">

<script>
function myFunction()
{ [Link]("demo").[Link] = "red";
}
</script>
</body>
</html>
Output:

In JavaScript, using the addEventListener() method, you can handle an event:


Syntax: [Link]("name_of_event", myScript);
Code: addEventListener( )

<html>
<body>
<p>Press a key inside the text field to set a red background color.</p>

51
Client-Side Scripting (Semester V)

<input type="text" id="demo">


<script>
[Link]("demo").addEventListener("keypress",
myFunction);

function myFunction()
{
[Link]("demo").[Link] = "red";
}
</script>
</body>
</html>

Output:

<!DOCTYPE html>
<html>
<head>
<title>Javascript Mouse Events</title>
<style>
#target-div {
width: 320px;
height: 150px;
background: blue;
margin-bottom: 10px;
}
</style>

52
Client-Side Scripting (Semester V)

<script>
function clickHandler(evt) {
var html = "[Link]=" + [Link];

[Link]("log-div").innerHTML = html;
}
</script>
</head>
<body>
<h3>Press Ctrl key and Click</h3>
<div id="target-div" onclick="clickHandler(event)" >
</div>
<div style="color:red;" id="log-div">
</div>
</body>
</html>
3.3 Changing an attribute value dynamically:
The change in any attribute value can be reflected to the user by highlighting
the value or text by some color.
The onchange event is associated with many elements <input>, <select> of
a form object and helpful to make call to a function where the change of
attribute value code is written.
In following example onchange event is used with two textboxes and
whenever user will make chage in value of these textboxes, text color and
background of text boxes will change.
Code: onchange event to change text color as blue and background color is
pink.

<html>
<head>
<script type="text/javascript">
function highlight(x)

53
Client-Side Scripting (Semester V)

{
[Link]="blue";
[Link]="pink";
}
</script>
</head>
<body>
<form name="myform" action=" " method="post">
Institute Name:
<input type="text" name="iname" onchange="highlight(this)"/>
<BR>
Program:
<input type="text" name="infotech" onchange="highlight(this)"/>
<br>
<input type="submit" value="submit" name="submit">
</form>
</body>
</html>
Output:

Code: onchange event to change the text in text box.

<html>
<body>
Enter some text:
<input type="text" name="txt" value="Hello"
onchange="myFunction([Link])">

<script>
function myFunction(val)
{
alert("The input value has changed. The new value is: " + val);
}
</script>

54
Client-Side Scripting (Semester V)

</body>
</html>
Output:

“with” keyword

The with keyword is used as a kind of shorthand for referencing an object's


properties or methods.
The object specified as an argument to with becomes the default object for
the duration of the block that follows. The properties and methods for the
object can be used without naming the object.
Syntax:
with (object)
{
Properties used without the object name and dot
}

Example:

Without using “with” keyword Use of “with” keyword


<html> <html>
<body> <body>
<h2>JavaScript Math functions <h2>JavaScript Math functions
without using "with"</h2> without using "with"</h2>
<script> <script>
var r = 10; var r = 10;
{ with (Math)
a = ([Link]) * r * r; {
x = r * [Link]([Link]); a = PI * r * r;
y = r * [Link]([Link] / 2); x = r * cos(PI);
z=[Link](16); y = r * sin(PI / 2);
} z=sqrt(16);
[Link]("a="+a+"<br>"); }
[Link]("x="+x+"<br>"); [Link]("a="+a+"<br>");
[Link]("y="+y+"<br>"); [Link]("x="+x+"<br>");
[Link]("z="+z+"<br>"); [Link]("y="+y+"<br>");

55
Client-Side Scripting (Semester V)

</script> [Link]("z="+z+"<br>");
</body> </script>
</html> </body>
</html>

Output: Output:

JavaScript Math functions JavaScript Math functions


without using "with" using "with"
a=314.1592653589793 a=314.1592653589793
x=-10 x=-10
y=10 y=10
z=4 z=4

3.4 Changing option list dynamically:

Code: Following example provides two radio buttons to the user one is for
fruits and another is for vegetables.

When user will select the fruits radio button, the option list should present
only the fruits names to user and when user will select the vegetable radio
button, the option list should present only the vegetable names to user so
that user can select an appropriate element of interest.

<html>
<body>
<html>
<script type="text/javascript">
function modifyList(x)
{
with([Link])
{
if(x ==1)
{
optionList[0].text="Kiwi";
optionList[0].value=1;
optionList[1].text="Pine-Apple ";
optionList[1].value=2;
optionList[2].text="Apple";

56
Client-Side Scripting (Semester V)

optionList[2].value=3;
}

if(x ==2)
{
optionList[0].text="Tomato";
optionList[0].value=1;
optionList[1].text="Onion ";
optionList[1].value=2;
optionList[2].text="Cabbage ";
optionList[2].value=3;
}
}
}

</script>
</head>
<body>
<form name="myform" action=" " method="post">
<select name="optionList" size="3">
<option value=1>Kiwi
<option value=1>Pine-Apple
<option value=1>Apple
</select>
<br>
<input type="radio" name="grp1" value=1 checked="true"
onclick="modifyList([Link])"> Fruits

<input type="radio" name="grp1" value=2


onclick="modifyList([Link])"> Vegitables
</form>
</body>
</html>
Output:

57
Client-Side Scripting (Semester V)

Code: Following example provides four list elements as name of branches.


When you select a branch from list, selected branch will be displayed as
output.

<html>
<body>
<p>Select Program from list:</p>
<select id="mySelect" onchange="myFunction()">
<option value="CO">Computer Engg</option>
<option value="IF">Information Technology</option>
<option value="EJ">Electronics and Tele</option>
<option value="CE">Chemical Engg</option>
</select>
<p id="demo"></p>
<script>
function myFunction()
{
var x = [Link]("mySelect").value;
[Link]("demo").innerHTML = "You selected: " + x;
}
</script>
</body>
</html>
Output:

3.5 Evaluating check box selections


A checkbox is created by using the input element with the type=”checkbox”
attribute-value pair.

58
Client-Side Scripting (Semester V)

A checkbox in a form has only two states (checked or un-checked).


Checkboxes can be grouped together under a common name.
Code: Following example make use of five checkboxes to provide five options
to the user regarding favorite color. After the selection of favorite colors, all
selected color names are displayed as output.

<html>
<head>
<title>Print value of all checked CheckBoxes on Button click.</title>
<script type="text/javascript">
function printChecked()
{
var items=[Link]('check_print');
var selectedItems="";
for(var i=0; i<[Link]; i++)
{
if(items[i].type=='checkbox' && items[i].checked==true)
selectedItems+=items[i].value+"<br>";
}
[Link]("y").innerHTML =selectedItems;
}
</script>
</head>
<body>
<big>Select your favourite accessories: </big><br>
<input type="checkbox" name="check_print" value="red">red<br>
<input type="checkbox" name="check_print" value="Blue">Blue<br>
<input type="checkbox" name="check_print"
value="Green">Green<br>
<input type="checkbox" name="check_print"
value="Yellow">Yellow<br>
<input type="checkbox" name="check_print"
value="Orange">Orange<br>
<p><input type="button" onclick='printChecked()' value="Click
me"/></p>
You Selected:
<p id="y"></p>
</body>
</html>

59
Client-Side Scripting (Semester V)

Output:

3.6 Changing labels dynamically


What is a label?
The <label>tag is used to provide a usability improvement for mouse users
i.e, if a user clicks on the text within the <label> element, it toggles the
control.
Approach:
 Create a label element and assign an id to that element.
 Define a button that is used to call a function. It acts as a switch to
change the text in the label element.
 Define a javaScript function, that will update the label text.
 Use the innerHTML property to change the text inside the label.
The innerHTML property sets or returns the HTML content of an element.

Code: Given an HTML document and the task is to change the text and color
of a label using JavaScript.

<html>
<head>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
Client-SideScripting
</h1>
<h4>
Click on the button to change the text of a label
</h4>
<label id = "aaa">
Welcome to Client-Side Scripting Course.
</label>

60
Client-Side Scripting (Semester V)

<br>
<button onclick="change_L()">
Click Here!
</button>

<script>
function change_L()
{
[Link]('aaa').innerHTML
= "CSS is a client-side scripting language.";
[Link]('aaa').[Link]
= "red";
}
</script>
</body>
</html>
Output:

3.7 Manipulating form elements


Javascript make it possible with help of hidden element which is similar to any
html element except it does not appear on screen.
Code: Following example is displaying the text of hidden text box after
clicking on submit button.

<html>
<head>
<title>
HTML Input Hidden value Property
</title>
</head>
<body style="text-align:center;">
<h1 style="color:green;">

61
Client-Side Scripting (Semester V)

Vidyalankar Polyetechnic
</h1>
<h2>Input Hidden value Property</h2>
<input type="hidden" id="it"
value="Information Technology">
<button onclick="disp_hidden_Text()">
Submit
</button>
<p id="demo" style="color:green;font-size:35px;"></p>
<script>
function disp_hidden_Text()
{
var x = [Link]("it").value;
[Link]("demo").innerHTML = x;
}
</script>
</body>
</html>
Output:

3.8 Intrinsic javascript functions


The HTML <input> src Attribute is used to specify the URL of the image to be
used as a submit Button. This attribute is not used with <input
type=”image”>
Syntax:
<input src="URL">
Attribute Values: It contains a single value URL which specifies the link of
source image. There are two types of URL link which are listed below:
 Absolute URL: It points to another webpage.
 Relative URL: It points to other files of the same web page.

62
Client-Side Scripting (Semester V)

Code: Following example we have used one <img> tag to simulate the
functionality of submit button. Before writing the code make sure one
“[Link]” picture should save in your folder.

<html>
<body>
<h1>The input src attribute</h1>

<form action=" ">


<label for="fname">Institute Name:</label>
<input type="text" id="name" name="name"><br><br>
<input type="image" src="[Link]" alt="Submit" width="130"
height="48" onclick="myFunction()">
</form>
<p id="demo"></p>
<script>
function myFunction()
{
var x = [Link]("name").value;
[Link]("You Submitted:<h2>" +x +"</h2>");
}
</script>
</body>
</html>
Output:

Disabling Elements:
It is common to display a form with some elements disabled, which prevents
the user from entering information into the element.
Code: Following example shows to enable and disable text field.

63
Client-Side Scripting (Semester V)

<html>
<body>
Name: <input type="text" id="myText">
<p>Click the button to enable/disable the text field.</p>
<button onclick="myFunction()">
change status
</button>
<script>
function myFunction()
{
var txt=[Link]("myText")
if ('disabled' in txt)
{
[Link]=![Link];
}
}
</script>
</body>
</html>
Output:

OR

<html>
<body>

First Name: <input type="text" id="myText"><br>


<br>
<button onclick="disableTxt()">Disable Text field</button>
<button onclick="undisableTxt()">Undisable Text field</button>

<script>
function disableTxt()

64
Client-Side Scripting (Semester V)

{
[Link]("myText").disabled = true;
}

function undisableTxt()
{
[Link]("myText").disabled = false;
}
</script>
</body>
</html>
Output:

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.
Set a text field to read-only:
[Link]("myText").readOnly = true;

Syntax:
To return the readOnly property: [Link]
To Set the readOnly property: [Link] = true|false

Code: Following example illustrate the use of read only property.


When user clicks on “Click here” button, text box is disabled.
<html>
<body>

Name: <input type="text" id="myText" value="VP">

<p>Click the button to set the text field to read-only.</p>

65
Client-Side Scripting (Semester V)

<p><strong>Tip:</strong> To see the effect, try to type something in the


text field before and after clicking the button.</p>

<button onclick="myFunction()">Click here </button>

<script>
function myFunction()
{
[Link]("myText").readOnly = true;
}
</script>

</body>
</html>

Output:

66

You might also like