Chapter 3
Form and Event Handling
Uses of Form:
Basics of a HTML Form
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.
Using Form Object with JavaScript:
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 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 |
Methods of form object:
Detecting Form Events:
onSubmit :It is called before data is submitted
onReset:
�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: �
its own name
its index in the array
document.order.elements[0]
�TextField: �
�TextField Cont.: �
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”
�Password Field: �
<form>
User name:<br>
<input type="text" name="username"><br>
User password:<br>
<input type="password" name="psw">
</form>
�TextArea: �
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.
�TextArea: �
�TextArea: �
<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.
�Button: �
<input type=“submit">
<input type=“reset">
�Check box: �
<input type="checkbox">
<form>
<input type="checkbox" name=“lang" value=“C++"> C++
</form>
�Radio Button: �
<input type=“radio">
<form>
<input type=“radio" name=“r1" value=“Option1"> O1
<input type=“radio" name=“r1" value=“Option2"> O2
</form>
�Drop Down List: �
<form >
<select name="color">
<option value=“Red">Red</option>
<option value=“Green">Green</option>
<option value=“Blue">Blue</option>
</select>
</form>
�Input Type Email: �
<form>
E-mail:
<input type="email" name="email">
</form>
�Input Events/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.
�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: �
<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: �
<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: �
�Changing Attribute values Dynamically: �
�Changing option list Dynamically: �
�Evaluating Checkbox Selection: �
Changing attribute value dynamically
element.setAttribute(attributename, attributevalue)
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");
Intrinsic JavaScript Functions:
Window object
Methods used with window
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.
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”);
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
Date Object
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)
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)
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
Math Constants
<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>
<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>
<h1>Section 2 : FIND SQUAREROOT,POWER,EXPONENTIAL</h1><br><br>
Enter no : <input type="text" id="t3"> </input>
<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>
<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>
Intrinsic JavaScript Functions:
Disabling Elements:
Disabling Elements Cont.:
<button>
<fieldset>
<input>
<optgroup>
<option>
<select>
<textarea>
Read Only Elements:
Return the readOnly property:
textObject.readOnly
Set the readOnly property:
textObject.readOnly = true|false
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>
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>