Chapter 3 Form and Event Handling
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]
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
• 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.
<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>
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.
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.
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>
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>
<html>
<body>
Name: <input type="text" id="myText">
<button onclick="myFunction()">Check</button>
<script>
function myFunction()
{
document.getElementById("myText").readOnly = true;
}
</script>
</body>
</html>