Unit 3 Forms Event Handling
Unit 3 Forms Event Handling
Unit 3
Form and Event Handling
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.
The <form> element can contain one or more of the following form elements:
<input>
<textarea>
<button>
<select>
<option>
<fieldset>
<label>
<legend>
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:
3
Client-Side Scripting (Semester V)
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)
6
Client-Side Scripting (Semester V)
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)
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
<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 :
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)
<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
Syntax:
[Link](tagname);
<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)
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
<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:
<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)
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.
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>
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
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>
TextArea
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>
</html>
Output:
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
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>
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
Property Description
31
Client-Side Scripting (Semester V)
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>
<script>
function myFunction()
{
var x = [Link]("programs").options[2].disabled =
true;
[Link]("programs").options[2].[Link] = "red";
}
</script>
</body>
</html>
Output:
<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.
onClick, onBlur,
checkbox
onFocus.
hidden none
onBlur, onFocus,
password
onSelect.
reset onReset
onFocus, onBlur,
select
onChange.
submit onSubmit
35
Client-Side Scripting (Semester V)
submit
reset
button
These events are fired when some click related activity is registered.
Form events:
blur onblur When the focus is away from a form element (The
onblur event occurs when an object loses focus.)
<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:
<html>
<body>
<p>When you submit the form, a function is triggered which alerts some
text.</p>
<script>
function myFunction()
{
alert("The form was submitted");
}
</script>
</body>
</html>
Output:
37
Client-Side Scripting (Semester V)
<html>
<body>
<script>
function myFunction()
{
var x = [Link]("fname");
[Link] = [Link]();
[Link]("fname").[Link]="blue";
}
</script>
</body>
</html>
Output:
Window/Document events:
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:
<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:
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.
<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)
<html>
<body>
<script>
function myFunction()
{
[Link]("aa").[Link] = "35px";
}
</script>
</body>
</html>
Output:
<html>
<body>
<h2>
42
Client-Side Scripting (Semester V)
<script>
function color_change()
{
[Link]("demo").[Link] = "red";
[Link]("demo").[Link] = "yellow";
}
</script>
</body>
</html>
Output:
<html>
<body>
43
Client-Side Scripting (Semester V)
}
</script>
</body>
</html>
Output:
<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:
<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>
______________-
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]
KeyEvent:
Event Description
48
Client-Side Scripting (Semester V)
1) The onkeydown event occurs when the user is pressing a key (on the
keyboard).
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.
<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>
<script>
function myFunction()
{ [Link]("demo").[Link] = "red";
}
</script>
</body>
</html>
Output:
<html>
<body>
<p>Press a key inside the text field to set a red background color.</p>
51
Client-Side Scripting (Semester V)
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:
<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
Example:
55
Client-Side Scripting (Semester V)
</script> [Link]("z="+z+"<br>");
</body> </script>
</html> </body>
</html>
Output: Output:
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
57
Client-Side Scripting (Semester V)
<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:
58
Client-Side Scripting (Semester V)
<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:
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:
<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:
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>
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>
<script>
function disableTxt()
64
Client-Side Scripting (Semester V)
{
[Link]("myText").disabled = true;
}
function undisableTxt()
{
[Link]("myText").disabled = false;
}
</script>
</body>
</html>
Output:
Syntax:
To return the readOnly property: [Link]
To Set the readOnly property: [Link] = true|false
65
Client-Side Scripting (Semester V)
<script>
function myFunction()
{
[Link]("myText").readOnly = true;
}
</script>
</body>
</html>
Output:
66