You are on page 1of 15

Chapter 3 : Form and Event Handling

1. Building blocks of a form, properties and methods of form ,button, text, textarea, checkbox, radio buttons, select element

Basics of Form
- Form is a fundamental unit used for collecting information
- It uses various components like button, textfield, textarea, checkboxes etc to collect information from user
- 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:
1. Name: It is a name of form. You can use forms without giving them names, but it is required, to easily used in JavaScript.
2. Method: It is either GET or POST; these are the two ways the data can be sent to server.
3. 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”>
- 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]

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

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.
 reset(): This method of form object is used to reset a form.
 submit(): This method of form object is used to submit a form.
- The method attribute specifies the HTTP method. (GET or POST) to be used when submitting the form data:
<form action="/action_page.php" method="get">
GET Method:
 The default method when submitting form data is GET.
 However, when GET is used, the submitted form data will be visible in the page address field:
 /action_page.php?firstname=Mickey&lastname=Mouse
 It appends form-data into the URL in name/value pairs
 The length of a URL is limited (about 3000 characters)
 Never use GET to send sensitive data! (will be visible in the URL)
 GET is better for non-secure data, like query strings in Google
POST Method:
 Always use POST if the form data contains sensitive or personal information.
 The POST method does not display the submitted form data in the page address field.
 POST has no size limitations, and can be used to send large amounts of data.

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.

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

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">
- The <button> tag also defines a clickable button. Inside a <button> element you can put content, like text or images. This is the difference
between this element and buttons created with the <input> element.
Example : <button>Default Button</button>
<button class="button">Styled Button</button>

Text Field
• 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” with default value “Hello” and allows to enter upto 20 characters data.
• JavaScript treats this as a text object.
• 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
use 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” or
document.username.value=“AAA”
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>

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”.
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.
checkbox
• 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">
Example :
<input type="checkbox" name="vehicle1" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle2" value="Car"> I have a car<br>
<input type="checkbox" name="vehicle3" value="Boat" checked> I have a boat<br>
radio buttons
• 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>

select element/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>
• By default, the first item in the drop-down list is selected.
• To define a pre-selected option, add the selected attribute to the option:
<option value="fiat" selected>Fiat</option>
• Use the size attribute to specify the number of visible values:
<select name="cars" size="3">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
• Use the multiple attribute to allow the user to select more than one value:
<select name="cars" size="4" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
Input Type Email:
• It is used for input fields that should contain an e-mail address.
• Depending on browser support, the e-mail addresscan 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>

2. Form events- mouse event, key events, form objects and elements

Events:
 An HTML event can be something the browser does, or something a user does.
 Often, when events happen, you may want to do something.
 JavaScript lets you execute code when events are detected.
 HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

Role of JavaScript in Events:


 Event handlers can be used to handle, and verify, user input, user actions, and browser actions.
 Things that should be done every time a page loads
 Things that should be done when the page is closed
 Action that should be performed when a user clicks a button
 Content that should be verified when a user inputs data

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
 onload: Occurs when the browser has finished loading the page.

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

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>

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>

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.

3.Changing attribute value dynamically, changing option list dynamically

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.
• 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)
Examples
1)var b = document.querySelector("button");
b.setAttribute("name", "helloButton");
b.setAttribute("disabled", "");
2) document.getElementById("sampleAnchor").setAttribute("href", "https://www.BitDegree.org");

Changing option list Dynamically:


• In JavaScript values can be changed 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.
• The add() method is used to add an option to a drop-down list.
selectObject.add(option, index)
• To remove an option from a drop-down list, use the remove() method.
selectObject.remove(index)
Examples:
1. Adding option at end of list
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option);
2. Adding option at beginning of list
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option, x[0]);
3. Adding option at a particular index of list
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option, x[2]);
4. Adding option before a selected option
var x = document.getElementById("mySelect");
if (x.selectedIndex >= 0)
{
var option = document.createElement("option");
option.text = "Kiwi";
var sel = x.options[x.selectedIndex];
x.add(option, sel);
}

4. Evaluating checkbox selection, changing a label dynamically

Evaluating Checkbox Selection:


1. The checked property sets or returns the checked state of a checkbox.
2. This property reflects the HTML checked attribute.
3. We can use a function to determine which checkbox is selected or whether selected or not.
function check() {
document.getElementById("myCheck").checked = true;
}

function uncheck() {
document.getElementById("myCheck").checked = false;
}
changing a label dynamically
2 properties can be used for changing the text dynamically:
1. innerHTML : it can add text alongwith formatting
Eg :
<script> document.getElementById('lblName').innerHTML = 'Hi, I am <b> Arun Banik </b>';
</script>
2. innerText : it allows us to add plain text values only
<script>let lbl = document.getElementById('lblEmp');
lbl.innerText = empName
</script>

6. Intrinsic JavaScript functions, disabling elements, read only elements

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.
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
• A new window can be opened asfollows:
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.
 A window can be closed as : windowname.close();
 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”);
2. 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”);

Document object

Several properties of the document object include information about the current document in general like
• document.URL specifies the document’s URL.
• document.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.
Date Object
• The Date object is used to work with dates and times.
• Date objects are created with new Date().
• Methods :
 getDate() : Returns the day of the month (from 1-31)
 getDay(): Returns the day of the week (from 0-6)
 getFullYear() Returns the year (four digits)
 getHours()Returns the hour (from 0-23)
 getMilliseconds() : Returns the milliseconds (from 0-999)
 getMinutes()Returns the minutes (from 0-59)
 getMonth()Returns the month (from 0-11)
 getSeconds() : Returns the seconds (from 0-59)
Math Object:
• The Math object allows you to perform mathematical tasks.
Methods :
 Math.random() : To create a random number
 Math.min() and Math.max(): can be used to find the lowest or highest value in a list of arguments
 Math.round(): rounds a number to the nearest integer
 Math.ceil(): rounds a number up to the nearest integer
 Math.floor(): rounds a number down to the nearest integer
 Math.cos(x):returns cosine of the angle specified in radians
 Math.sin(x):returns sine of the angle specified in radians
 Math.tan(x):returns tangent of the angle specified in radians
 Math.exp(x):Returns value of E^x
 Math.pow(x,y):returns value of x to power y
 Math.sqrt(x): Returns squareroot of the number
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
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.
• The disabled attribute can be used on the following elements:
<button>
<fieldset>
<input>
<optgroup>
<option>
<select>
<textarea>
Ex:
<html>
<body>
<button id=“b1">Click</button>
<button onclick=“fun1()">Check</button>
<script>
function myFunction(){
document.getElementById(“b1").disabled = true;
}
</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.
• 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.Disabling 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>

You might also like