Forms Event Handling
Forms Event Handling
Unit 3
Form and Event Handling
Unit Outcome:
1. Write JavaScript to design a form to accept input values for the given problem.
3.1: Building blocks of a Form, properties and methods of form, button, text, text area,
checkbox, radio button, select element.
1
Client-Side Scripting (Semester V)
Forms are one of the most common web page elements used with JavaScript.
➢ To add functionality that makes forms easier for users to fill out
➢ To validate or process the data that a user enters before that 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:
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:
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)
Syntax:
3
Client-Side Scripting (Semester V)
12 <input type = “text”> “text” onchange A single line text entry field.
4
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. 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;
5
Client-Side Scripting (Semester V)
}
</style>
</head>
<body>
<form action=" ">
<fieldset>
<legend>Personalia:</legend>
<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 = document.getElementById("fname").value;
document.getElementById("demo").innerHTML = y;
var x = document.getElementById("lname").value;
document.getElementById("demo1").innerHTML = x;
var z = document.getElementById("email").value;
document.getElementById("demo2").innerHTML = z;
var w = document.getElementById("birthday").value;
document.getElementById("demo3").innerHTML = w;
6
Client-Side Scripting (Semester V)
}
</script>
</body>
</html>
Output:
• 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.
7
Client-Side Scripting (Semester V)
Properties of Form:
Methods of Form:
Methods of Events:
<html> <head>
<script type="text/javascript">
function assign()
{
document.forms.book.title.value="CSS_book";
document.forms.book.author.value="Manisha Padwal";
}
</script>
8
Client-Side Scripting (Semester V)
</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>
</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.
9
Client-Side Scripting (Semester V)
Syntax:
document.getElementById(elementID);
Code: Following code displays after clicking on button, text color is changed as red.
<html>
<body>
<script>
function myFunction()
{
var x = document.getElementById("demo");
x.style.color = "red";
}
</script>
</body>
</html>
Output:
2. getElementsByName() method
10
Client-Side Scripting (Semester V)
Syntax:
document.getElementsByName(name);
Code: Check all <input> elements with type="checkbox" in the document that have a
name attribute with the value "animal":
<html>
<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 = document.getElementsByName("program");
var i;
for (i = 0; i < x.length; i++)
{
if (x[i].type == "checkbox")
{
x[i].checked = true;
}
}
}
</script>
</body>
</html>
11
Client-Side Scripting (Semester V)
Output:
3. getElementsByTagName() method
Syntax:
document.getElementsByTagName(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 = document.getElementsByTagName("LI");
12
Client-Side Scripting (Semester V)
document.getElementById("demo").innerHTML = x.length;
}
</script>
</body>
</html>
Output:
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 = document.getElementsByTagName("P");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "pink";
x[i].style.color = "blue";
}
13
Client-Side Scripting (Semester V)
}
</script> </body> </html>
Output:
4) getElementsByClassName() Method
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>
document.getElementsByClassName('greenBorder example')[0]
.style.border="10px solid green";
document.getElementsByClassName('yellowBorder example')[0]
.style.border="10px solid yellow";
</script>
</body>
</html>
Output:
15
Client-Side Scripting (Semester V)
5) innerHTML property
<html>
<body>
<script type="text/javascript">
function changeText()
{
document.getElementById('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 = document.getElementById("myDIV").getElementsByTagName("P");
document.getElementById("demo").innerHTML = x.length;
17
Client-Side Scripting (Semester V)
var y = document.getElementById("myh").getElementsByTagName("H2");
document.getElementById("demo1").innerHTML = y.length;
}
</script>
</body>
</html>
Output:
Code:
<script type="text/javascript">
function changeText()
{
var userInput = document.getElementById('userInput').value;
document.getElementById('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:
18
Client-Side Scripting (Semester V)
Code:
<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 = document.getElementById("userInputName").value;
document.getElementById("vp").innerHTML = userInputName;
var userInputPwd = document.getElementById("userInputPwd").value;
document.getElementById("vp1").innerHTML = userInputPwd;
}
</script>
</body>
</html>
Output:
19
Client-Side Scripting (Semester V)
<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:
<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.
20
Client-Side Scripting (Semester V)
In this example, we are going to display the password strength when releases the key
after press.
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>
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
21
Client-Side Scripting (Semester V)
Button:
2. Submit, which is associated to the form and which starts the loading of the file
assigned to the action attribute.
A Button object also represents an HTML <button> element which is specified as follows:
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.
Syntax:
22
Client-Side Scripting (Semester V)
OR
<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()
{
alert("Hello world!");
}
</script>
</body>
</html>
Output:
Code:
<html>
<body>
23
Client-Side Scripting (Semester V)
Code:
<html>
<body>
<p id="demo">Click me.</p>
<script>
document.getElementById("demo").onclick = function()
{
myFunction()
};
function myFunction()
{
document.getElementById("demo").innerHTML = "YOU CLICKED ME!";
}
</script>
</body>
</html>
24
Client-Side Scripting (Semester V)
Output:
Text:
Input “text” is an object to enter a single line of text whose content will be part of form
data.
Code:
<script type="text/javascript">
function changeText()
{
var userInput = document.getElementById('userInput').value;
document.getElementById('vp').innerHTML = userInput;
}
</script>
TextArea
25
Client-Side Scripting (Semester V)
The <textarea> tag indicates a form field where the user can enter a large amount of
text.
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.
• "Off“: sets a textarea to ignore all wrapping and places the text
into one ongoing line.
textareaObject.wrap = soft/hard/off
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>
26
Client-Side Scripting (Semester V)
Output:
<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 = document.getElementById("myTextarea").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
27
Client-Side Scripting (Semester V)
Output:
Methods of TextArea:
Method Description
select() Selects the entire contents of a text area
<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 = document.getElementById("myTextarea").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Output:
28
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).
<html>
<body>
<div>
Program:
<br>
<input type="checkbox" name="program" id="it" value="IT">
<label for="it">Information Tech</label> <br>
29
Client-Side Scripting (Semester V)
<button onclick="validate();">Validate</button>
</div>
<div id="status">
</div>
<script>
function validate()
{
var elements = document.getElementsByName("program");
var statusText = " ";
for (var index=0;index < elements.length;index++)
{
statusText = statusText +
elements[index].value+"="+elements[index].checked+"<br>";
}
document.getElementById("status").innerHTML = statusText;
}
</script>
</body>
</html>
Output:
Radio Button:
30
Client-Side Scripting (Semester V)
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.
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:
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 = document.getElementsByName("br");
for(var i = 0; i < obj.length; i++)
{
if(obj[i].checked == true)
{
if(confirm("You have selected " + obj[i].value))
return true;
else
return false;
31
Client-Side Scripting (Semester V)
}
}
}
</script>
</body>
</html>
Output:
Select:
Form SELECT elements (<select>) within your form can be accessed and manipulated in
JavaScript via the corresponding Select object.
Option Object
32
Client-Side Scripting (Semester V)
Property Description
label Sets or returns the value of the label attribute of an option in a drop-
down list
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>
33
Client-Side Scripting (Semester V)
<option>Information Technology</option>
<option>Chemical Engineering</option>
<option>Electronics & TeleComm.</option>
</select>
<p>Click the button to disable the third option (index 2) in the dropdown list.</p>
<script>
function myFunction()
{
var x = document.getElementById("programs").options[2].disabled = true;
document.getElementById("programs").options[2].style.color = "red";
}
</script>
</body>
</html>
Output:
<html>
34
Client-Side Scripting (Semester V)
<body>
Select a Program and click the button:
<select id="mySelect">
<option>Information Technology</option>
<option>Computer Engg</option>
<option>Civil Engg</option>
<option>Electronics and Telecommunication</option>
</select>
<button type="button" onclick="myFunction()">
Display index</button>
<script>
function myFunction()
{
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect").options;
alert("Index: " + y[x].index + " is " + y[x].text);
}
</script>
</body>
</html>
Output:
35
Client-Side Scripting (Semester V)
3. 2 Form Events:
The form property within the document object contains an array of all forms defined within
the document.
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.
hidden none
reset onReset
submit onSubmit
36
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.
• 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.)
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>
37
Client-Side Scripting (Semester V)
function focusevent()
{
document.getElementById("input1").style.background=" green";
}
</script>
</body>
</html>
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>
38
Client-Side Scripting (Semester V)
Output:
<html>
<body>
<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 = document.getElementById("fname");
x.value = x.value.toUpperCase();
document.getElementById("fname").style.color="blue";
}
</script>
</body>
</html>
Output:
Window/Document events:
39
Client-Side Scripting (Semester V)
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
<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>
40
Client-Side Scripting (Semester V)
<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 = window.outerWidth;
var h = window.outerHeight;
var txt = "Window size: width=" + w + ", height=" + h;
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
Output:
41
Client-Side Scripting (Semester V)
d
Output:
Mouse Events:
<html>
<html>
<body>
<img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="1"
src="aa.jpg" width="64" height="64">
<script>
function bigImg(x)
{
x.style.height ="120px";
x.style.width ="120px";
42
Client-Side Scripting (Semester V)
}
function normalImg(x)
{
x.style.height = "64px";
x.style.width = "64px";
}
</script>
</body> </html>
Output:
When you roll the mouse over the paragraph either up or down, paragraph text will be
increased to 35 pixels.
<html>
<body>
<script>
function myFunction()
{
document.getElementById("aa").style.fontSize = "35px";
}
</script>
43
Client-Side Scripting (Semester V)
</body>
</html>
Output:
<html>
<body>
<h2>
<p id="demo" ondblclick="color_change()">Double-click me to change my text
color.</p> </h2>
<script>
function color_change()
{
document.getElementById("demo").style.color = "red";
document.getElementById("demo").style.backgroundColor = "yellow";
}
</script>
</body>
</html>
Output:
<html>
<body>
44
Client-Side Scripting (Semester V)
Execute a JavaScript when the user right-clicks on a <div> element with a context menu:
<html>
<head>
<style>
div {
background: yellow;
45
Client-Side Scripting (Semester V)
Execute a JavaScript when moving the mouse pointer over a <div> element and display
the x and y coordinates.
<html>
<head>
46
Client-Side Scripting (Semester V)
<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>
function myFunction(e)
{
var x = e.clientX;
var y = e.clientY;
var coor = "Coordinates: (" + x + "," + y + ")";
document.getElementById("demo").innerHTML = coor;
}
</script>
</body>
</html>
Output:
47
Client-Side Scripting (Semester V)
<!DOCTYPE HTML>
<html>
<head>
<style>
body{font-family:Verdana;
background:#44c767; color:#fff;}
</style>
<script>
var count = 0;
function tracker(){
count++;
function popup1() {
function popup2() {
48
Client-Side Scripting (Semester V)
</script>
</head>
<body>
</body>
</html>
______________-
<!DOCTYPE HTML>
<html>
</head>
<body>
49
Client-Side Scripting (Semester V)
</body>
<script>
var p = document.getElementById("content");
function change(){
this.style.background ="#FA8B7C";
this.style.fontFamily ="Verdana";
this.style.padding ="10px";
this.style.color ="#fff";
</script>
</html>
http://www.tutorialspark.com/javascript/JavaScript_Mouse_Event.php
KeyEvent:
Event Description
50
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:
2) The onkeyup event occurs when the user releases a key (on the keyboard).
You can handle the keyup event with the onkeyup event handler.
51
Client-Side Scripting (Semester V)
The following example will show you an alert message when the keyup event occurs.
<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).
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, 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.
<html>
<body>
<p>Press a key inside the text field to set a red background color.</p>
52
Client-Side Scripting (Semester V)
<script>
function myFunction()
{ document.getElementById("demo").style.backgroundColor = "red";
}
</script>
</body>
</html>
Output:
Code: addEventListener( )
<html>
<body>
<p>Press a key inside the text field to set a red background color.</p>
function myFunction()
{
document.getElementById("demo").style.backgroundColor = "red";
}
</script>
</body>
53
Client-Side Scripting (Semester V)
</html>
Output:
<!DOCTYPE html>
<html>
<head>
<style>
#target-div {
width: 320px;
height: 150px;
background: blue;
margin-bottom: 10px;
</style>
<script>
function clickHandler(evt) {
document.getElementById("log-div").innerHTML = html;
</script>
54
Client-Side Scripting (Semester V)
</head>
<body>
</div>
</div>
</body>
</html>
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)
{
x.style.color="blue";
x.style.backgroundColor="pink";
}
</script>
</head>
<body>
55
Client-Side Scripting (Semester V)
<html>
<body>
Enter some text:
<input type="text" name="txt" value="Hello" onchange="myFunction(this.value)">
<script>
function myFunction(val)
{
alert("The input value has changed. The new value is: " + val);
}
</script>
</body>
</html>
Output:
56
Client-Side Scripting (Semester V)
“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)
Example:
57
Client-Side Scripting (Semester V)
</script> document.write("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(document.forms.myform)
{
if(x ==1)
{
optionList[0].text="Kiwi";
optionList[0].value=1;
optionList[1].text="Pine-Apple ";
58
Client-Side Scripting (Semester V)
optionList[1].value=2;
optionList[2].text="Apple";
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(this.value)"> Fruits
59
Client-Side Scripting (Semester V)
Output:
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 = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>
</body>
</html>
Output:
60
Client-Side Scripting (Semester V)
A checkbox is created by using the input element with the type=”checkbox” attribute-value
pair.
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=document.getElementsByName('check_print');
var selectedItems="";
for(var i=0; i<items.length; i++)
{
if(items[i].type=='checkbox' && items[i].checked==true)
selectedItems+=items[i].value+"<br>";
}
document.getElementById("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>
61
Client-Side Scripting (Semester V)
</body>
</html>
Output:
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
62
Client-Side Scripting (Semester V)
</h4>
<label id = "aaa">
Welcome to Client-Side Scripting Course.
</label>
<br>
<button onclick="change_L()">
Click Here!
</button>
<script>
function change_L()
{
document.getElementById('aaa').innerHTML
= "CSS is a client-side scripting language.";
document.getElementById('aaa').style.color
= "red";
}
</script>
</body>
</html>
Output:
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>
63
Client-Side Scripting (Semester V)
<title>
HTML Input Hidden value Property
</title>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
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 = document.getElementById("it").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Output:
64
Client-Side Scripting (Semester V)
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.
Code: Following example we have used one <img> tag to simulate the functionality of
submit button. Before writing the code make sure one “submit.jpg” picture should save
in your folder.
<html>
<body>
<h1>The input src attribute</h1>
65
Client-Side Scripting (Semester V)
Disabling Elements:
It is common to display a form with some elements disabled, which prevents the user
from entering information into the element.
<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=document.getElementById("myText")
if ('disabled' in txt)
{
txt.disabled=!txt.disabled;
}
}
</script>
</body>
</html>
Output:
66
Client-Side Scripting (Semester V)
OR
<html>
<body>
<script>
function disableTxt()
{
document.getElementById("myText").disabled = true;
}
function undisableTxt()
{
document.getElementById("myText").disabled = false;
}
</script>
</body>
</html>
Output:
67
Client-Side Scripting (Semester V)
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:
document.getElementById("myText").readOnly = true;
Syntax:
To return the readOnly property: textObject.readOnly
To Set the readOnly property: textObject.readOnly = true|false
<p><strong>Tip:</strong> To see the effect, try to type something in the text field
before and after clicking the button.</p>
<script>
function myFunction()
{
document.getElementById("myText").readOnly = true;
}
</script>
</body>
</html>
Output:
68
Client-Side Scripting (Semester V)
69