1 of 48

Chapter 3

Form and Event Handling

2 of 48

Uses of Form:

  • Collect information from customer or from student through online registration.
  • Forms are used for online Survey.
  • Conducting online examination, for getting Feedback and so on.
  • Information present in the form is submitted to server for further processing.

3 of 48

Basics of a HTML Form

  • Forms are among the most useful features of the HTML language.
  • An HTML form begins with the <form>tag.
  • This tag indicates that a form is beginning and it enables form elements to be used.
  • It has following three parameters:

Name: It is a name of form. You can use forms without giving them

names, but it is required, to easily used in javascript.

Method: It is either GET or POST; these are the two ways

the data can be sent to server.

Action: It is the script that the form data will be sent to when

submitted.

  • Ex: <form name=“order” method=“get” action=“A.jsp”>
  • For the form that will be processed entirely by javascript the method and action attributes are not needed. You can use directly as follows:
  • Ex: <form name=“order”>

4 of 48

Using Form Object with JavaScript:

  • Each form in your HTML page is represented in JavaScript by a form object, which has a same name attribute in the <form> tag that you used to define.
  • Alternately you can use the forms array to refer to forms.
  • This array includes an item for each form element, indexed starting with ‘0’.
  • Ex: If the first form in a document has the name form1, it can be referred by two ways:

document.form1

document.forms[0]

5 of 48

Properties of Form Object:

Attribute

Description

action

It is the form’s ACTION Attribute, or the program to which the form data will be submitted.

method

It Specifies the HTTP methods used to submit the form. such as GET,POST.

GET – Defalult. Appends the form data to the URL in name/value Pairs

POST Send the form-data as an HTTP post transaction

name

This attribute denotes the name of the form

Target

It specifies the window in which the result of the form will be displayed. Normally this is done in main window, replacing the form itself.

The target values can be as follows:

1. _blank:Open in a new window

2. _self :opens in the same frame as it was clicked (default)

3. _parent:open in the parent frameset .

4. _top:opens in the full body of the window

5. framename:opens in named frame

6 of 48

Methods of form object:

  • You can use these form methods to submit the data or reset the form yourself, without requiring user to press button.
  • Actually this facility is provided for the situations where user is clicking the image or performs any other action but wants to submit the form data, then these methods will be helpful.
  • reset(): This method of form object is used to reset a form.
  • submit(): This method of form object is used to submit a form.

7 of 48

Detecting Form Events:

  • The form object has two event handlers as follows:

onSubmit :It is called before data is submitted

onReset:

  • You can prevent the submission or resetting by returning a false value from onSubmit or onReset event handler.
  • You can specify a group of javascript statements or a function call for these events within a <form> tag that defines the form.

8 of 48

�The form can be written inside as <body> tag as follows : �

<body>

<form name=“form1” action=“/my.jsp” method=“GET” target=“_blank”>

//code for placing form controls here

</form>

</body>

9 of 48

�Scripting Form Elements: �

  • The most important property of the form object is the elements array, which contains an object for each of the form elements.
  • The element can be referred by:

its own name

its index in the array

  • Ex: document.order.name1

document.order.elements[0]

10 of 48

�TextField: �

  • It is the most commonly used form element.
  • You can use it to prompt for a name, address or any other information.
  • With javascript you can display the text automatically in the textfield.
  • Syntax:
  • <input type=“text” name=“t1” value=“Hello” size=“20”>
  • It creates a text field called “t1” default value “Hello” and allows to enter upto 20 characters data.
  • JavaScript treats this as a text object.

11 of 48

�TextField Cont.: �

  • Each text object has following properties:

name: It is the name given to text field. This is also used

as the object name.

defaultValue: It is the default value and corresponds to the

VALUE attribute. It is read-only property.

value: It is the current value. It starts with defaultValue

but can be changed either by user or by function.

Many times we are using this attribute to read the

value entered by user or to change the value

Ex: Following Ex. changes the textfield value:

document.order.username.value=“AAA”

12 of 48

�Password Field: �

  • The characters in a password field are masked (shown as asterisks or circles).
  • Textfield can be created with a password field effect.
  • Ex:

<form>

User name:<br>

<input type="text" name="username"><br>

User password:<br>

<input type="password" name="psw">

</form>

13 of 48

�TextArea: �

  • These are defined with their own tag <textarea> and represented by textarea object.
  • Textarea allows user to enter multiline data which is not possible with textfield.
  • A text area can hold an unlimited number of characters, and the text renders in a fixed-width font (usually Courier).

  • The size of a text area can be specified by the cols and rows attributes, or even better
  • Ex:
  • <textarea name=“ta1” rows=“2” cols=“30”>

This is a TextArea.

</textarea>

It creates a textarea called “ta1” with 2 rows and 30 cols. The text between the tags <textarea></textarea> is displayed as a default initial value of it.

14 of 48

�TextArea: �

  • These are defined with their own tag <textarea> and represented by textarea object.
  • Textarea allows user to enter multiline data which is not possible with textfield.
  • A text area can hold an unlimited number of characters, and the text renders in a fixed-width font (usually Courier).
  • The size of a text area can be specified by the cols and rows attributes.
  • If not mentioned default row value is “2” and cols value is “20”.

15 of 48

�TextArea: �

  • Ex:

<textarea name=“ta1” rows=“2” cols=“30”>

This is a TextArea.

</textarea>

It creates a textarea called “ta1” with 2 rows and 30 cols. The text between the tags <textarea></textarea> is displayed as a default initial value of it.

16 of 48

�Button: �

  • Buttons use input tag and can be used with one of three different types:
  • type=“button”: It is a generic button. It performs no action on its own, but you can assign it one using a javascript event hndler.
  • type=“submit”: It is a submit button. It causes the data in the form fields to be sent to script.
  • type=“reset”: It is a reset button. It sets all the form fields back to their default value or blank.
  • Ex: <input type="button">

<input type=“submit">

<input type=“reset">

17 of 48

�Check box: �

  • It is a form element that looks like a small box.
  • Clicking on it switches between the checked and unchecked states.
  • Checkboxes let a user select ZERO or MORE options of a limited number of choices.
  • Syntax:

<input type="checkbox">

  • Ex:

<form>

<input type="checkbox" name=“lang" value=“C++"> C++

</form>

18 of 48

�Radio Button: �

  • Another element for decisions is the radio button.
  • These are similar to check boxes, but they exist in groups and only one button can be checked in the group.
  • Syntax:

<input type=“radio">

  • Ex:

<form>

<input type=“radio" name=“r1" value=“Option1"> O1

<input type=“radio" name=“r1" value=“Option2"> O2

</form>

19 of 48

�Drop Down List: �

  • It is useful for multiple choice selections.
  • The <select> HTML tag is used to define selection list or drop down list of text items.
  • The content between the opening <option> and closing </option> tags is what the browsers will display in a drop-down list.
  • Ex:

<form >

<select name="color">

<option value=“Red">Red</option>

<option value=“Green">Green</option>

<option value=“Blue">Blue</option>

</select>

</form>

20 of 48

�Input Type Email: �

  • It is used for input fields that should contain an e-mail address.
  • Depending on browser support, the e-mail address can be automatically validated when submitted.
  • Some smartphones recognize the email type, and add ".com" to the keyboard to match email input.
  • Ex:

<form>

E-mail:

<input type="email" name="email">

</form>

21 of 48

�Input Events/Form Events: �

  • There are following types of Form Events:

onchange: Occurs when element changes

onselect: Occurs when element is selected

onblur: Occurs when element loses focus

onfocus: Occurs when element gets focus

onsubmit: Occurs when user clicks submit button

onreset: Occurs when user clicks reset button

Key Events:

onkeydown: Occurs when user is pressing/holding down key

onkeypress: Occurs when user presses a key

onkeyup: Occurs when user releases a key

The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers. To detect only whether the user has pressed a key, use the onkeydown event instead, because it works for all keys.

22 of 48

�Mouse Events: �

  • There are following types of Mouse Events:

onmouseover/onmouseout: When mouse passes over an element

onmousedown/onmouseup: When pressing/releasing a mouse

button

onmousedown: When mouse is clicked

onmousemove/onmouseout: When moving a mouse pointer

onclick: When mouse is clicked

ondblclick: When a mouse is double clicked

23 of 48

�document.getElementById() method: �

  • The document.getElementById() method returns the element of specified id.
  • We can use document.getElementById() method to get value of any field. But we need to define id for the input field.
  • Ex:

<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>

24 of 48

�document.getElementsByName() method: �

  • The document.getElementsByName() method returns all the element of specified name.
  • Syntax: document.getElementsByName("name")
  • Ex:

<script type="text/javascript">

function totalelements() {

var allgenders=document.getElementsByName("gender");

alert("Total Genders:"+allgenders.length);

}

</script>

<form>

Male:<input type="radio" name="gender" value="male">

Female:<input type="radio" name="gender" value="female">

<input type="button" onclick="totalelements()" value="Total Genders">

</form>

25 of 48

�Form Objects: �

  • Webpage contains various elements including Window as first element.
  • Window contains Document Object
  • The objects are represented in following hierarchical order:
  • Window Object: Present at the top of hierarchy
  • Document Object: Every HTML document which loads into a window is document object that contains page elements.
  • Form Object: All tags enclosed in <form> </form> sets form object
  • Form Control Elements: All controls like text fields, button, checkbox, radio button etc.

26 of 48

�Changing Attribute values Dynamically: �

  • In javascript value of any attribute can be changed dynamically.
  • To achieve this onchange event is used as it executes a script when user changes a value of an element.

27 of 48

�Changing option list Dynamically: �

  • In javascript values can be change at runtime according to user input.
  • Option list is used to show list of items where user can select any one.
  • You can change the option list’s value according to choice or user input.

28 of 48

�Evaluating Checkbox Selection: �

  • The checked property sets or returns the checked state of a checkbox.
  • This property reflects the HTML checked attribute.
  • We can use a function to determine which checkbox is selected or whether selected or not.

29 of 48

Changing attribute value dynamically

  • The setAttribute() method adds the specified attribute to an element, and gives it the specified value.

  • If the specified attribute already exists, only the value is set/changed.
  • Syntax:

element.setAttribute(attributename, attributevalue)

30 of 48

Changing attribute value dynamically

var b = document.querySelector("button");

b.setAttribute("name", "helloButton");

b.setAttribute("disabled", "");

document.getElementById("sampleAnchor").setAttribute("href", "https://www.BitDegree.org");

31 of 48

Intrinsic JavaScript Functions:

  • They are the in built functions which can be used with JavaScript objects
  • Various objects supported by JavaScript include document, window, Date , Math , Array, String etc.

32 of 48

Window object

  • The window object represents an open window in a browser.
  • The window object is used for creating a new window for displaying a documents

33 of 48

Methods used with window

  • A new window can be opened as follows:

Winobj = window.open(“URL”, “Windowname”, “FeatureList”);

1. Winobj : is the variable to store new window object

2. URL : it is the location of the file that must be loaded in the window

3. Windowname: It is the name assigned to the window

4. Feature List: it includes a list of features for the window like width, height etc.

34 of 48

ii. A window can be closed as : windowname.close();

iii. Dialog Boxes: Following dialogboxes can be used with Window object:

1. Alert : It is used for displaying an alert box which gives message to user. It is used as window.alert(“Message”);

    • Confirm: It displays a confirmation dialog box that can be used to select either of the 2 options OK or CANCEL. IT is used as

window.confirm(“Message”);

3. Prompt: It is used to display a prompt box to the user for accepting the input. It is used as window.prompt(“Message”);

35 of 48

Document object

Several properties of the document object include information about the current document in general like

  • document.URL specifies the document’s URL.
  • idocument.title lists the title of the current page, defined by the HTML <title> tag.
  • document.referrer is the URL of the page the user was viewing prior to the current page—usually, the page with a link to the current page.
  • document.lastModified is the date the document was last modified. This date is sent from the server along with the page.
  • document.bgColor and document.fgColor are the background and foreground(text) colors for the document, corresponding to the BGCOLOR and TEXT attributes of the <body> tag.
  • document.cookie enables you to read or set a cookie for the document.

36 of 48

Date Object

  • The Date object is used to work with dates and times.
  • Date objects are created with new Date().
  • Methods :

i. getDate() : Returns the day of the month (from 1-31)

ii. getDay(): Returns the day of the week (from 0-6)

iii. getFullYear() Returns the year (four digits)

iv. getHours()Returns the hour (from 0-23)

v. getMilliseconds() : Returns the milliseconds (from 0-999)

vi. getMinutes()Returns the minutes (from 0-59)

vii. getMonth()Returns the month (from 0-11)

viii. getSeconds() : Returns the seconds (from 0-59)

37 of 48

Date Object Cont.:

ix. setDate() : Sets the day of the month of a date object

x. setFullYear() : Sets the year (four digits) of a date object

xi. setHours():sets the hour (from 0-23)

xii. setMilliseconds() : sets the milliseconds (from 0-999)

xiii. setMinutes()sets the minutes (from 0-59)

xiv. setMonth()sets the month (from 0-11)

xv . setSeconds() : sets the seconds (from 0-59)

38 of 48

Math Object:

The Math object allows you to perform mathematical tasks. Methods :

i. Math.random() : To create a random number

ii. Math.min() and Math.max(): can be used to find the lowest or highest value in a list of arguments

iii. Math.round(): rounds a number to the nearest integer

iv. Math.ceil(): rounds a number up to the nearest integer

v. Math.floor(): rounds a number down to the nearest integer

vi.Math.cos(x):returns cosine of the angle specified in radians

vii.Math.sin(x):returns sine of the angle specified in radians

viii.Math.tan(x):returns tangent of the angle specified in radians

ix.Math.exp(x):Returns value of E^x

x.Math.pow(x,y):returns value of x to power y

xi.Math.sqrt(x): Returns squareroot of the number

39 of 48

Math Constants

  • Math.PI         // returns PI
  • Math.SQRT2      // returns the square root of 2
  • Math.SQRT1_2    // returns the square root of ½
  • Math.LN2        // returns the natural logarithm of 2
  • Math.LN10       // returns the natural logarithm of 104

40 of 48

<html>

<head>

<title> Using math object</title>

<script language="javascript">

  function findmax(t1,t2)

{ alert("Maximum number is :" + Math.max(t1,t2)); }

function findmin(t1,t2)

{ alert("Minimum number is :" + Math.min(t1,t2)); }

  function squareroot(t1)

{ alert(Math.sqrt(t1)); }

function power(t1)

{

t2=prompt("Enter power:");

alert("Power of " + t1 +"^" + t2 + "=" + Math.pow(t1,t2));

}

  </script>

</head>

</html>

41 of 48

<body>

<p> <h2> Using Math Object you can find min,max,squareroot,average,randon number etc </h2></p>

<form>

<h1>Section 1 : FIND MAX AND MIN Numbers </h1> <br><br>

Enter no 1 : <input type="text" id="t1"> </input><br>

Enter no 2 : <input type="text" id="t2"> </input><br>

<button id="b1" onClick= findmax (getElementById('t1') . value,getElementById('t2').value)> MAX </button>

<button id="b2" onClick= findmin(getElementById('t1'). value,getElementById('t2').value)> MIN</button>

<hr>

 

42 of 48

<h1>Section 2 : FIND SQUAREROOT,POWER,EXPONENTIAL</h1><br><br>

Enter no : <input type="text" id="t3"> </input>&nbsp;&nbsp;

<button id="b3" onClick=squareroot(getElementById('t3').value)> SQUARE ROOT</button>

<button id="b4" onClick=power(getElementById('t3').value)> POWER </button>

<hr>

<h1>Section 3 : FIND SIN,COS and TAN for an angle</h1><br><br>

Enter angle in radians: <input type="text" id="t4"> </input>&nbsp;&nbsp;

<button id="b5" onClick=alert(Math.sin(getElementById('t4').value))> SINE</button>

<button id="b6" onClick=alert(Math.cos(getElementById('t4').value))> COSINE</button>

<button id="b7" onClick=alert(Math.sin(getElementById('t4').value))> TAN</button>

 

</form>

 </body>

</html>

43 of 48

Intrinsic JavaScript Functions:

  • JavaScript provides the intrinsic functions for Submit and Reset button.
  • One can use these functionalities while submitting and resetting the form fields.
  • The submit() method of form object can be used to send the form to the server similar to same way when user presses the submit button.

44 of 48

Disabling Elements:

  • The disabled attribute is a boolean attribute.
  • When present, it specifies that the element should be disabled.
  • A disabled element is unusable.
  • The disabled attribute can be set to keep a user from using the element until some other condition has been met (like selecting a checkbox, etc.).
  • Then, a JavaScript could remove the disabled value, and make the element usable.

45 of 48

Disabling Elements Cont.:

  • The disabled attribute can be used on the following elements:

<button>

<fieldset>

<input>

<optgroup>

<option>

<select>

<textarea>

46 of 48

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.
  • Tip: To prevent the user from interacting with the field, use the disabled property instead.
  • Syntax:

Return the readOnly property:

textObject.readOnly

Set the readOnly property:

textObject.readOnly = true|false

  • true|false Specifies whether a text field should be read-only or not true - The text field is read-only
  • false - Default. The text field is changeable

47 of 48

Disabling Elements Ex:

<html>

<body>

<button id=“b1">Click</button>

<button onclick=“fun1()">Check</button>

<script>

function myFunction()

{

document.getElementById(“b1").disabled = true;

}

</script>

</body>

</html>

48 of 48

readonly Elements Ex:

<html>

<body>

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

<button onclick="myFunction()">Check</button>

<script>

function myFunction()

{

document.getElementById("myText").readOnly = true;

}

</script>

</body>

</html>