Unit-3 Form and Event Handling

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 74

UNIT 3 10 M

FORM AND EVENT


HANDLING
BUILDING BLOCKS OF A FORM
� An HTML form is a section of a document which contains
controls such as text fields, password fields, checkboxes,
radio buttons, submit button, menus etc.
� HTML Form is a document which stores information
entered by user on a web server using interactive
controls.
� It contains different kind of information such as
username, password, contact number, email id etc.
� HTML form uses elements like input box, radio
buttons, check box, submit buttons etc.
� Using these elements the information of an user is
submitted on a web server
� HTML Forms are required, when you want to collect
some data from the site visitor.
� For example, during user registration you would like
to collect information such as name, email address,
credit card, etc.
� The HTML <form> tag is used to create an HTML
form and it has following syntax

<form >
// form Elements
</form>
PROPERTIES AND METHODS OF FORM
� action : (specify an url)Backend script ready to process
your passed data.
� method : Method to be used to upload data. The most
frequently used are GET and POST methods.
⚫ post: We can use the post value of method attribute when we
want to process the sensitive data as it does not display the
submitted data in URL.
⚫ get: The get value of method attribute is default value while
submitting the form. But this is not secure as it displays data in
URL after submitting the form.
� target : Specify the target window or frame where the
result of the script will be displayed. It takes values like
_blank, _self, _parent,_top etc.
⚫ self: If we use _self as an attribute value, then the response will
display in current page only.
⚫ blank: If we use _blank as an attribute it will load the response
in a new page.
� name: it specifies a name used to identify the form.
METHODS OF FORM
�reset()-it is
used to reset a form .
Event name =onreset()

�submit()-it isused to submit a form.


Event name =onsubmit()
//program to demonstrate onsubmit() event name
<html>
<head>
<script>
function pass()
{
alert("submit");
}
</script>
</head>
<body>
<form onsubmit="pass()">
Name<input type="text" value="text"><br>
<input type="submit“ value="submit"><br>
</form>
</body>
</html>
�//program to demonstrate onreset() event
<html>
<head>
<script>
function clean()
{
alert(“Reset");
}
</script>
</head>
<body>
<form onreset=“clean()">
Name<input type="text“ value="text"><br>
<input type=“reset“ value=“Reset"><br>
</form>
</body>
</html>
� HTML form contains following four elements:

1. input: it is used to specify input field for user.


2. textarea: it is used to specify for multi-line text input
field for user.
3. button: it is used to perform an operation in a form
by the user.
4. label: it is used to give label to any tag like button,
input etc.
HTML FORM INPUT ELEMENT
� The HTML <input> element is most used form
element.
� Input element can be displayed in many ways,
depending on the type attribute.

1. <input type=“text”>: displays a single line text input


field.
2. <input type=“radio”>:displays a radio button.
3. <input type=“checkbox”>:displays checkbox.
4. <input type=“submit”>:displays submit button.
5. <input type=“button”>:displays a clickable button.
WRITE A JAVASCRIPT TO DESIGN A FORM TO ACCEPT
VALUES FOR USER ID & PASSWORD.
<html>
<body>
<form name=“login”>
Enter Username<input type=“text” name=“userid”><br>
Enter Password<input type=“password” name=“pswrd”><br>
<input type=“button” onclick=“display()” value=“signIn”>
</form>
<script language=“javascript”>
function display()
{
document.write("User ID "+ login.userid.value + "Password :
"+login.pswrd.value);
}
</script>
</body>
</html>
BUTTON ELEMENT
� Button object represents a clickable button in a HTML
Form.
� It is used to activate a JavaScript when a user clicks
on it.
� In JavaScript we can create button using <input>
element or <button> element.
� Using <input> element, type attribute specify three
types of buttons :
⮚ Normal button , submit button and reset button.
� Syntax:

<input type=“button”>
or
<button type=“button”>...</button>
BUTTON OBJECT PROPERTIES
Reset object(button):
� It represents reset button in an HTML Form.

� When clicking on a reset button , it resets all the


controls within the form to their default values.
� Syntax:

<input type=“reset”>

Submit object(button):
� It represents submit button in an HTML Form.

� It sends the user input in the form to the server.

� When clicking on a submit button, it fires on submit


event.
<input type=“submit”>
<html>
<head>
<title>button demo</title>
</head>
<body>
<form name=“frm1”>
<input type=“submit” name=“s” value=“SUBMIT”>
<input type=“reset” name=“r” value=“RESET”>
<input type=“button” name=“b” value=“CLICK”>
</form>
</body>
</html>
TEXT OBJECT(ELEMENT)
� Text object represents a single-line text input field
in an HTML form.
� User can provide input by entering single line text
into text field.
� Syntax:

<input type=“text”>
� Example:

<input type=“text”name=“n1” size=“30”


maxlength=“30” value=“Example”>
TEXTAREA OBJECT
� Textarea object represents a multiline text-area in an
HTML form.
� Syntax:

<textarea> . . . </textarea>

� Example:
<textarea name=“example1” cols=“50” rows=“50”>
</textarea>
CHECKBOX OBJECT
� The input element defines an input field. when you specify
type attribute as “checkbox "of this element then checkbox
is created.
� Checkbox object represents a checkbox in an HTML form.
� It allows the user to select one or more options from the
available choices.
� Syntax:

<input type= “checkbox”>


� Example:

<input type=“checkbox” name=“example1” value=“check1”>


Check1
<input type=“checkbox” name=“example” value=“check2 ”
checked> Check2
CHECKBOX OBJECT PROPERTIES
RADIO OBJECT
� Radio object represents a radio button in an HTML
form.
� The input element defines an input field. when you
specify type attribute as “radio "of this element then
radio button is created .
� Syntax:
<input type= “radio”>
� Example:

<input type=“radio” name=“example1” value=“yes”> Yes


<input type=“radio” name=“example1” value=“no”
checked> No
SELECT OBJECT
� Select object represents a dropdown list in an HTML
form.
� It allows the user to select one or more options from
the available choices.
� Syntax:

<select> … </select>
OPTION OBJECT
� Option object represents an HTML <option>
element.
� It is used to add items to a select element.
� Syntax:

<option value> . . . </option>


// Simple Program on select and Option Object Method
<html>
<head>
<script type="text/javascript">

function optionfruit(select)
{
var a = select.selectedIndex;
var fav = select.options[a].value;
if(a==0)
{
alert("Please select a fruit");
}
else
{
document.write("Your Favorite Fruit is <b>"+fav+".</b>");
}
}
</script>
</head>
<body>
<form>
List of Fruits:
<select name="fruit">
<option value="0">Select a Fruit</option>
<option value="Mango">Mango</option>
<option value="Apple">Apple</option>
<option value="Banana">Banana</option>
<option value="Strawberry">Strawberry</option>
<option value="Orange">Orange</option>
</select>
<input type="button" value="Select" onclick="optionfruit(this.form.fruit);">
</form>
</body>
</html>
OUTPUT
FORM EVENTS
� 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, js react
over these events and allow the execution. This
process of reacting over the events is called Event
Handling. Thus, js handles the HTML events
via Event Handlers.
� For example, when a user clicks over the browser,
add js code, which will execute the task to be
performed on the event.
HTML EVENTS AND THEIR EVENT HANDLERS ARE
// Simple Program on onsubmit() & onfocus() Event handler
<html>
<body>
<script>
function validateform()
{
var uname=document.myform.name.value;
var upassword=document.myform.password.value;
if (uname==null || uname=="")
{
alert("Name cannot be left blank");
return false;
}
else if(upassword.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
}
function emailvalidation()
{
var a=document.myform.email.value
if (a.indexOf("@")==-1)
{

alert("Please enter valid email address");


return false;
document.myform.email.focus()
}
}
</script>
<body>
<form name="myform" method="post"
action="validpage.html" onsubmit="return
validateform()">

Email: <input type="text" size="20" name="email"


onblur="emailvalidation()"> <br>

User Name: <input type="text" name="name"><br>

Password: <input type="password“ name="password">


<br>
<input type="submit" value="Submit" >
</form>
</body>
</html>
File name: validpage.html

<html>
<body>
<script type="text/javascript">
alert("You are a Valid User !!!");
</script>
</body>
</html>
OUTPUT:
MOUSEOVER EVENT AND MOUSEOUT EVENT
<html>
<body>
<p onmouseover=“over()” onmouseout=“out()”>THIS IS MOUSE
EVENT</p>
<p>The function over() is triggered when the user moves the mouse
pointer over the text</p>
<p>The function out() is triggered when the mouse pointer is moved
out of the text</p>
<script>
function over()
{
alert(“mouseover");
}
function out()
{
alert(“mouseout");
}
</script>
KEYDOWN EVENT
<html>
<body>
<p>A function is triggered when the user is pressing
a key in the input field.</p>
<input type="text" onkeydown="myFunction()">
<script>
function myFunction()
{
alert("You pressed a key inside the input
field");
}
</script>
</body>
</html>
KEYUP EVENT
<html>
<body>
<p>A function is triggered when the user releases a key in the
input field. The function transforms the character to upper
case.</p>
Enter your name: <input type="text" id="fname"
onkeyup="myFunction()">
<script>
function myFunction()
{
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
KEYPRESS EVENT
<html>
<body>
<p>A function is triggered when the user is pressing a
key in the input field.</p>
<input type="text" onkeypress="myFunction()">
<script>
function myFunction()
{
alert("You pressed a key inside the input field");
}
</script>
</body>
</html>
FORM OBJECTS AND ELEMENTS
� Document Object Model:
� The document object represents the whole html
document.
� When html document is loaded in the browser, it
becomes a document object.
� You can access a <form> element by using
getElementById():
� The document.getElementById() method returns
the element of specified id.
METHODS OF DOCUMENT OBJECT
� We can access and change the contents of document by
its methods.
� The important methods of document object are as
follows:
ACCESSING FIELD VALUE BY DOCUMENT OBJECT
� Here, we are using document.form1.name.value to
get the value of name field.
� Here, document is the root element that represents
the html document.
� form1 is the name of the form.
� name is the attribute name of the input text.
� value is the property, that returns the value of the
input text.
//WAP to find Cube of Number using getElementById
<html>
<body>
<script type="text/javascript">
function getcube()
{
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number"
name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
</body>
</html>
CHANGING ATTRIBUTE VALUE DYNAMICALLY
� In JavaScript, we can change the attribute value of
any form elements dynamically. That means we can
assign new value to that attribute using function and
that function will be execute when event triggered.
� Steps:

1) Select the element whose style properties needs to


be change.
2) Use element.style property to set the style
attribute of an element.
3) Set the properties either by using bracket
notation or dash notation.
4) Write function and call it on any event.
� This example changing the color, background-color and
width property of elements.
<html>
<head>
<title>
How to change style attribute of an element dynamically using
JavaScript ?
</title>
</head>
<body>
<center>
<h1 id = "h1" style = "color:green;" > JavaScript
</h1>
<p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;">
</p>
<button onclick = "gfg_Run()"> Click here</button>
<p id = "GFG_DOWN" style =
"font-size: 23px; font-weight: bold; color: green; ">
</p>
<script>
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
var heading = document.getElementById("h1");
el_up.innerHTML = "Click on the button to " + "change the style
attribute";
function gfg_Run()
{
heading.style["color"] = "white";
heading.style["background-color"] = "green";
heading.style["width"] = "300px";
heading.style["border"] = "1px solid black";
el_up.style["background-color"] = "green";
el_up.style["width"] = "400px";
el_up.style["border"] = "1px solid black";
el_down.innerHTML = "Style Attribute Changed";
}
</script>
</center>
</body>
</html>
OUTPUT: BEFORE AND AFTER CLICK
CHANGING OPTION LIST DYNAMICALLY
� In JavaScript, we can change the option list of pull
down menu dynamically at the run time according to
the user choice.
� We can add new options in the existing list or remove
the options already added.
� Steps:

1) Create the html <select> element with


<option>element.
2) Using <option> element to add items into <select>
element.
3) Write function and call it on any events.
<html>
<head>
<title>Dynamically add/remove options select - JavaScript</title>
</head>
<body>
<script>
function addOption()
{
var select = document.getElementById("dynamic-select");
select.options[select.options.length] = new Option('New Element',
'0', false, false);
}
function removeOption()
{
var select = document.getElementById("dynamic-select");
select.options[select.selectedIndex] = null;
}
function removeAllOptions(){
var select = document.getElementById("dynamic-select");
select.options.length = 0;
}
</script>
<select id="dynamic-select">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<button onclick="addOption()">add item</button>
<button onclick="removeOption()">remove
item</button>
<button onclick="removeAllOptions()">remove
all</button>

</body>
</html>
OUTPUT:
EVALUATING CHECKBOX SELECTION:
� 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) and is independent of the state of other
checkboxes in the form. Check boxes can be grouped
together under a common name.
� You can write JavaScript function that evaluates
whether or not a check box was selected and then
processes the result according to the needs of your
application.
� Following example make use of five checkboxes to
provide five options to the user regarding fruit.
<html>
<head> <title> Html Forms</title>
<script language=“javascript”>
function selection()
{ var x ="You selected: ";
with(document.forms.myform)
{
if(a.checked == true)
{ x+= a.value+ " ";}
if(b.checked == true)
{ x+= b.value+ " "; }
if(o.checked == true)
{ x+= o.value+ " "; }
if(p.checked == true)
{ x+= p.value+ " "; }
if(g.checked == true)
{ x+= g.value+ " "; }
document.write(x); }
}
</script>
</head>
<body>
<form name="myform" action="" method=“post”>
Select Your Favourite Fruits:
<input type=“checkbox” name=“a” value=“Apple”>Apple
<input type=“checkbox” name=“b” value=“Banana”>Banana
<input type=“checkbox” name=“o” value=“Orange”>Orange
<input type=“checkbox” name=“p” value=“Pear”>Pear
<input type=“checkbox” name=“g” value=“Grapes”>Grapes
<input type=“reset” value=“Show” onclick=“selection()”>
</form>
</body>
</html>
OUTPUT:
� After click

You selected: Banana


CHANGING LABEL DYNAMICALLY
� In JavaScript we can change the label dynamically at
the run time that means we can assign new value to
the existing label and preserved previous value of
that label by using function and that function will be
execute when event triggered.
� Main purpose is to achieved reusability of an element
and in this case relabeling an element when the
purpose of that element is already been served.
<html>
<head>
<title> changing label</title>
<script language="JavaScript">
function show(e)
{
with(document.forms.frm1)
{
if(e=='state')
{
b1.value='city'
op1[0].text=“Maharashtra"
op1[0].value=1;
op1[1].text="Goa"
op1[1].value=2;
op1[2].text="Tamilnadu"
op1[2].value=3;
}
if(e=='city')
{
b1.value='state'
op1[0].text="Pune"
op1[0].value=1;
op1[1].text="Mumbai"
op1[1].value=2;
op1[2].text="sangli"
op1[2].value=3;
}
}
}
</script> </head> <body>
<form name="frm1" action="" method="post">
<select name="op1" size="3">
<option value=1>Maharashtra</option>
<option value=2> Goa</option>
<option value=3> Tamilnadu</option>
</select> <br>
<input type="submit“ name="submit" value="submit“>
<input type="reset" name="b1" value="city" onclick="show(this.value)">
</form>
</body>
</html>
OUTPUT:
MANIPULATING FORM ELEMENTS
o JavaScript provides us facility to manipulate elements
on a form after the user clicks submit button and
before the form is actually submitted to the
CGI(Common Gateway Interface) application.
o JavaScript makes it possible with help of hidden
element which is similar to any HTML element except it
doesn't appear on screen.
o Many times form fields are hidden and at the time of
form submission these fields assigned with hidden
values should be submitted.
o A hidden element has a name and value that is sent to
the CGI program along with other elements of the form
for processing.
o Syntax:<input type=“hidden” name=“” value=“”>
<html>
<head>
<script>
function assign()
{
with(document.forms.frm1)
{
alert("email ");
if(f.value.length>0 && l.value.length>0)
{
e.value=f.value+l.value+"@GMAIL.COM";
document.write(e.value);
}
}
}
</script>
</head>
<body>
<form name="frm1">
FIRST NAME<input type="text" name="f"/><BR>
LAST NAME<input type="text" name="l"/><BR>
EMAIL<input type="hidden" name="e"><BR>
<input type="button" name="SUBMIT" value="SUBMIT" onclick="assign()"/>
</form>
</body>
</html>
INTRINSIC JAVASCRIPT FUNCTION
oIntrinsicfunctions means the built in functions that
are provided by JavaScript.
oThe JavaScript provides the intrinsic functions for
Submit or Reset button. One can use these
functionalities while submitting the form or resetting
the form fields.
oThe submit() method of the form object can be used to
send the form to the server in exactly same way as if the
user has pressed the Submit button.
oJavascript provides built in objects like
Array,Boolean,Date,Error,Function,Math,Number,Objec
t,RegExp and string objects.
oEach of these objects holds several built in functions to
perform object related functionality.
FOLLOWING ARE SOME BUILT IN FUNCTIONS:-

1. isNaN()
� isNaN() method determines whether value of a variable is a
legal number or not.
� For example
document.write(isNan(0)); // false
document.write(isNan('JavaScript')); // true

2. eval()
� eval() is used to execute Javascript source code.
� It evaluates or executes the argument passed to it and generates
output.
� For example
eval("var number=2;number=number+2;document.write(number)");
//4
3. String()
� String() function converts the object argument
passed to it to a string value.
� For example

document.write(new Boolean(0)); // false


document.write(new Boolean(1)); // true
document.write(new Date()); // Tue Jan 05 2021
13:28:00 GMT+0530
4. parseInt()
� parseInt() function takes string as a parameter and
converts it to integer.
� For example

document.write(parseInt("45")); // 45
document.write(parseInt("85 days")); // 85
document.write(parseInt("this is 9")); // NaN
4.parseFloat()
� parseFloat() function takes a string as parameter
and parses it to a floating point number.
� For example

document.write(parseFloat("15.26")); // 15.26
document.write(parseFloat("15 48 65")); // 15
document.write(parseFloat("this is 29")); // NaN
document.write(pareFloat(" 54 ")); // 54

5. Date(): return current date.


<html>
<body>
<form name="myform">
Roll Number:<input type="text" name="roll"/><br/> <br/>
Name :<input type="text" name="name"/><br/><br/>

<img src ="C:\Users\DELL\Desktop\submit.png" height="40"


width="50"
onclick="javascript:document.forms.myform.submit()"/>

<img src ="C:\Users\DELL\Desktop\reset.png" height="40"


width="50"
onclick="javascript:document.forms.myform.reset()"/>
</form>
</body>
</html>
OUTPUT:
DISABLING ELEMENTS
� In JavaScript ,sometimes we need to enable and
disable input elements like textbox,radio
button,checkbox,label etc. However,every time
when we make a change we need to reload HTML
page.
� An element can be disabled in HTML by setting
disable property to true and enabled again by
disabled=false.
� We can disable some elements to restrict data
entry into those elements. such disabled elements
are displayed on the form but users are not able
to enter information in these elements.
<html>
<body>
<button id="myBtn">My Button</button> <br><br>
<button onclick="disableBtn()">Disable "My Button"</button>
<button onclick="enableBtn()">Enable "My Button"</button>
<script>
function disableBtn()
{
document.getElementById("myBtn").disabled = true;
}

function enableBtn()
{
document.getElementById("myBtn").disabled = false;
}
</script>
</body>
</html>
OUTPUT:
After disabled After enable
READ ONLY ELEMENTS
� We can restrict the user from changing the value of
an element by setting its readOnly property to
true,if we want to enter a value in that element
then set readOnly property to false.
<html>
<head>
<script>
function readfun()
{
document.getElementById("t1").readOnly=true;
}
function writefun()
{
document.getElementById("t1").readOnly=false;
}
</script>
</head>
<body>
<form name="myform">
Username: <input type="text“ id="t1"/><br/> <br/>
<input type="button" value="Read-only" onclick="readfun()"/>
<input type="button" value="write" onclick="writefun()"/>
</form></body></html>

You might also like