Chap 03 Form - and - Event - Handling
Chap 03 Form - and - Event - Handling
Unit 3
Form and Event Handling
Unit Contents
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
Unit Outcomes
✓ Write JavaScript to design a form to accept input values
for the given problem.
✓ Use JavaScript to implement form events to solve the
given problems.
✓ Develop JavaScript to dynamically assign specified
attribute value to the given form control.
✓ Use the given intrinsic functions with specified
parameters.
Introduction to Form
✓Forms are one of the most common web page elements used
with JavaScript.
➢To validate or process the data that a user enters before that data
is submitted to a server side script.
Building Blocks of a Form
• 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:
1. Text box for entering a line of text.
2. Push button for selecting an action.
3. Radio buttons for making one selection among a group of options.
4. Check boxes for selecting or deselecting a single, independent
option.
Example
<html>
<head>
<title> Demonstrating HTML Forms </title>
</head>
<body>
<form name = “DemoForm” action = “ ” method = “GET”>
Enter your name: <input type = “text” name = “text1”> <br>
<input type = “button” name = “button1” value = “Click” onclick = "show()" >
</form>
</body>
</html>
Output
Form Object and Elements
The form object is represented by HTML <form> element.
Syntax
<html>
<body>
<head> <form id="fullname">
<title> Assigning Values </title> <input id="name"> <br> <br>
<script type="text/javascript"> <input id="surname"> <br> <br>
function assign() <input type="button" id="btn" value="Assign
{ Values" onclick="assign()">
document.forms.fullname.name.value="Siddhesh"; </form>
</body></html>
document.forms.fullname.surname.value="Vaidya";
}
</script> </head>
Output
Properties and Methods of Form
•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.
Methods of Events
Sr. No. Methods Description
1 onReset Code is executed when the form is reset.
2 onSubmit Code is executed when form is submitted.
▪Forms and the elements they contain can be
selected from a document using standard methods
like:
1. getElementById()
2. getElementsByName()
3. getElementsByTagName()
4. innerHTML Property
getElementById()
•It returns a reference to the elements by its ID.
Syntax:
element = document.getElementById(id);
where,
•element is a reference to an element object, or null if an element with
the specified ID is not in the document.
•id is a case sensitive string representing the unique ID of the element
being sought.
Example
<html>
<body>
<p id="demo">Click the button to change the color of this paragraph.</p>
<p id="demo1">Click the button to change the color of this paragraph.</p>
<button onclick="myFunction()">Change Color</button>
<script>
function myFunction()
{
var x = document.getElementById("demo");
var y = document.getElementById("demo1"); Output
x.style.color = "green";
y.style.color = "red";
}
</script>
</body>
</html>
getElementsByName()
• It returns a collection of all elements in the document with the specified
name (the value of the name attribute).
Syntax:
•element = document.getElementsByName(name);
where,
•element is a reference to an element object.
•name is a case sensitive string representing the name of the element
being sought.
Example
<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");
for (var i = 0; i < x.length; i++) Output
{
if (x[i].type == "checkbox")
{
x[i].checked = true;
}
}
}
</script>
</body>
</html>
getElementsByTagName()
•It returns an HTMLCollection of elements with the given tag name. The complete
document is searched, including the root.
•The returned HTMLCollection is live, meaning that it updates itself automatically
to stay in sync with the DOM tree without having to all
document.getElementsByTagName() again.
Syntax:
elements = document.getElementsByTagName(tagname);
where,
elements is a live HTMLCollection of found elements in the order they appear in
the tree.
name is a string representing the name of the elements.
The special string “*” represents all elements.
Example 1
<html>
<body>
<strong><p>An unordered list:</p></strong>
<ul>
<li>Information Technology</li>
<li>Computer Engineering</li>
<li>Chemical Engineering</li>
<li>Civil 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");
document.getElementById("demo").innerHTML = x.length;
}
</script>
</body>
</html>
Output
Example 2
<html>
<body>
<p>Computer Engineering</p>
<p>Information Technology</p>
<p>Electronics and Telecommunication</p>
<button onclick="myFunction()">Try it</button>
<script> Output
function myFunction()
{
var x = document.getElementsByTagName("p");
for (var i = 0; i < x.length; i++)
{
x[i].style.backgroundColor = "lightgreen";
x[i].style.color = "red";
}
}
</script>
</body>
</html>
innerHTML Property
•The easiest way to modify the content of an HTML element is by using
the innerHTML property.
Syntax:
document.getElementById(id).innerHTML = new HTML;
Example 1: To change the text by using 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
Example 2: Script to count the number of <p> tag and <h2> tag
<html>
<style>
div
{ <script>
border: 1px solid black; function myFunction()
margin: 5px; {
} var x =
</style> document.getElementById("myDIV").getEleme
<body> ntsByTagName(“p");
<div id="myDIV"> document.getElementById("demo").innerHTML
<p>Information Technology</p> = x.length;
<p>Computer Engg.</p> var y =
<p>Electronics and Telecommunication</p> document.getElementById("myh").getElements
<p>Chemical Engg.</p> ByTagName("h2");
</div> document.getElementById("demo1").innerHTM
<div id="myh"> L = y.length;
<h2>Vidyalankar Polytechnic</h2> }
<h2>Vidyalankar Institute of Technology </h2> </script>
</div> </body>
<button onclick="myFunction()">Try </html>
it</button>
<p id="demo"></p>
<p id="demo1"></p>
Output
Example 3: Change content by providing user input
<html>
<body>
<p>Welcome <b id="vp">JavaScript</b> </p>
<input type="text" id="userInput" value="Enter Text Here"> <br> <br>
<input type="button" onclick="changeText()" value="Change Text">
<script>
function changeText()
{
var userInput = document.getElementById("userInput").value;
document.getElementById("vp").innerHTML = userInput;
}
</script>
</body>
</html>
Output
Example 4: Displaying user input by clicking on button
<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
Example 5: Generate alert after clicking on submit button
<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" value="">
<input type="submit" value="Submit">
</form> Output
<script>
function myFunction()
{
alert("The form was submitted");
}
</script>
</body>
</html>
Button
•Button is created by using following code:
<form method = “GET” action = “”>
<input type = “button” name = “MyButton” value = “Click” onclick = “msg()”>
<form>
<html> <body>
<div>
Program: <script>
<input type="checkbox" function validate()
name="program" id="it" value="IT"> {
<label for="it">Information var elements =
Tech</label> document.getElementsByName("program");
<input type="checkbox" var statusText = " ";
name="program" id="co" value="CO" for (var index=0;index <
checked> elements.length;index++)
<label for="co">Computer {
Engg</label> statusText = statusText +
<input type="checkbox" elements[index].value+"-
name="program" id="ej" value="EJ"> "+elements[index].checked+"<br>";
<label for="ej">Electronics</label> }
<button
onclick="javascript:validate();">Validat document.getElementById("status").innerHTML
e</button> = statusText;
</div> }
<div id="status"> </div> </script> </body> </html>
Output
Radiobutton
✓The radiobutton 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
<input type="radio" id="male" name="gender" value="male">
Example
<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"> Output
</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;
} } } </script>
Select
Form SELECT elements (<select>) within your form can be accessed and
manipulated in JavaScript via the corresponding Select object.
</select> }
Output
Form Events
✓One of the primary ways in which JavaScript is executed on a Web Pages is
through events. An event is a specific circumstance that is monitored by
JavaScript and that the script can respond in some way.
✓JavaScript enabled web pages are typically event driven. Events are actions
that occur on the webpage.
✓In order to make a web page more interactive, the script needs to be able to
access the contents of the document and know when the user is interacting
with it.
•The kinds of events that might occur are due to:
1. A document loading
2. The user clicking a mouse button
3. The browser screen changing size
Following are the HTML
intrinsic event attributes
onload onblur
onunload onkeypress
onclick onkeydown
onkeyup
ondblclick
onsubmit
onmousedown onreset
onmouseup onselect
onmouseover onchange
onmousemove
onmouseout
onfocus
Event Handler
•When a function is assigned to an event handler, that function is executed when
that event occurs.
•A handler that is assigned from a script used.
• Syntax: ‘[element].[event] = [function];’
where,
◦ [element] is a page element.
◦ [event] is the name of the selected event.
◦ [function] is the name of the function that occurs when the event takes place.
Example: document.onclick = clickHandler();
<html>
<head>
<title>Events</title>
<script>
function react()
{
alert("Please enter any value");
}
</script></head>
<body>
<form name = "myform" action = "" method = "post" onmousedown = "react()">
<input value = "Click mouse here">
</form>
</body>
</html>
Event Object & Event Listeners
•An event object provides information about the element that has
generated an event and enables to retrieve it in the script. An event
listener is essentially a mechanism that instructs an object to respond to
a particular kind of event.
Where,
• The first parameter is case insensitive string which specifies the type of
event like “click” or “mousedown”.
• The second parameter is the function we want to call when the event
occurs.
◦ The onkeypress event occurs when the user presses a key (on the
keyboard). The order of events related to the onkeypress event:
1. onkeydown
2. onkeypress
3. onkeyup
<html>
<body>
<br>
<input type="text" onkeypress="myFunction()">
<script>
function myFunction()
{
alert("You pressed a key inside the input field");
}
</script>
</body>
</html>
Changing Attribute Values
Dynamically
✓ JavaScript provides us facility to change an attribute of an element by
assigning a new value to the attribute at runtime.
✓We can write the code of change in attribute value in a user defined
function and can call that function when an appropriate event occurs.
✓The change in any attribute value can be reflected to the user by
highlighting the value or text by some colour.
✓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.
✓The onchange event occurs when the value of an element has been
changed or the cursor is moved away from the element. For
radiobuttons and checkboxes, the onchange event occurs when the
checked state has been changed
Example 1
<html>
<script type="text/javascript">
function highlight(x)
{
x.style.color="blue";
x.style.backgroundColor="pink";
}
</script>
<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>
Example 2
<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>
Changing Option List
Dynamically
✓We can change options in the option list at runtime by writing the code
in function.
✓The purpose of an option list is to present a user two or more items for
choice. Elements in option list are usually set when the option list is
created. However, you can change the content of an option list at
runtime by using a JavaScript function.
<html> if(x == 2)
<body> {
<html> optionList[0].text="Tomato";
<script type="text/javascript"> optionList[0].value=1;
function modifyList(x) optionList[1].text="Onion ";
{ optionList[1].value=2;
with(document.forms.myform) optionList[2].text="Cabbage ";
{ optionList[2].value=3;
if(x ==1) }}} </script>
{ <body>
optionList[0].text="Kiwi"; <form name="myform" action=" " method="post">
optionList[0].value=1; <select name="optionList" size="3">
optionList[1].text="Pine-Apple "; <option value=1>Kiwi
optionList[1].value=2; <option value=1>Pine-Apple
optionList[2].text="Apple"; <option value=1>Apple
optionList[2].value=3; </select><br>
} <input type="radio" name="grp1" value=1 checked="true"
onclick="modifyList(this.value)"> Fruits
<input type="radio" name="grp1" value=2
onclick="modifyList(this.value)"> Vegitables </form>
</body>
</html>
<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>
Evaluating Checkbox Selection
•A checkbox is created by using the input element with the
type=”checkbox” attribute-value pair.
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.
<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>
<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>
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.
<html>
<body style="text-align:center;">
<h1 style="color:green;"> Vidyalankar Polytechnic </h1>
<h2>Input Hidden value Property</h2>
<input type="hidden" id="it" value="Computer Engineering">
<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>
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.
<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="Submit.jpg" alt="Submit" width="130" height="150"
onclick="myFunction()">
</form>
<p id="demo"></p>
<script>
function myFunction()
{
var x = document.getElementById("name").value;
document.write("You Submitted:<h2>" +x +"</h2>");
}
</script>
</body>
</html>
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> Method 1
<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>
<html>
<body>
First Name: <input type="text" id="myText"><br><br> Method 2
<button onclick="disableTxt()">Disable Text field</button>
<button onclick="undisableTxt()">Undisable Text field</button>
<script>
function disableTxt()
{
document.getElementById("myText").disabled = true;
}
function undisableTxt()
{
document.getElementById("myText").disabled = false;
}
</script>
</body>
</html>
Read Only Elements
•The readOnly property sets or returns whether a text field is read-only, or
not.
•A read-only field cannot be modified. However, a user can tab to it,
highlight it, and copy the text from it.
•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
<html>
<body>
Name: <input type="text" id="myText" value="VP">
<p>Click the button to set the text field to read-only.</p>
<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()
{
document.getElementById("myText").readOnly = true;
}
</script>
</body>
</html>