0% found this document useful (0 votes)
141 views

Javascript Form Events

The document discusses form objects in JavaScript. It defines a form object as a browser object used to access HTML forms. It lists properties like name, action, method, target, elements, encoding, and length. It also discusses properties for specific form elements like buttons, checkboxes, file uploads, hidden fields, passwords, radio buttons, resets, selects, submits, and textareas. Methods like reset() and submit() are also summarized.

Uploaded by

Vaibhav Sarode
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
141 views

Javascript Form Events

The document discusses form objects in JavaScript. It defines a form object as a browser object used to access HTML forms. It lists properties like name, action, method, target, elements, encoding, and length. It also discusses properties for specific form elements like buttons, checkboxes, file uploads, hidden fields, passwords, radio buttons, resets, selects, submits, and textareas. Methods like reset() and submit() are also summarized.

Uploaded by

Vaibhav Sarode
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

CSS[22519]

Unit -IIIR.S.{MOBILE
MR.SWAMI Form NO:-+91-8275265361]
and Event Handling (Marks: 10)

Remember level Understand level Apply level

2 4 4

Form Object
 Form object represents an HTML form.

 It is used to collect user input through elements like text fields, check box and
radio button, select option, text area, submit buttons and etc.

Form Object:
form object is a Browser object of JavaScript used to access an HTML form. If a
user wants to access all forms within a document then he can use the forms array.
The form object is actually a property of document object that is uniquely created
by the browser for each form present in a document. The properties and methods
associated with form object are used to access the form fields, attributes and
controls associated with forms.

Syntax:
<form>
//form element
</form>

Form element Attributes :


name:
name property of form object denotes the form name.
CSS[22519]
Action : MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

The action attribute defines the action to be performed when the form is submitted.

Usually, the form data is sent to a file on the server when the user clicks on the
submit button.

This property is a read or write property and its value is a string.

Method:
method property of form object is used to access the method attribute present in
HTML associated with the <form> tag.
This property is a read or write property and its value is a string.

The method attribute specifies the HTTP method to be used when submitting
the form data.The form-data can be sent as URL variables
(with method="get") or as HTTP post transaction (with method="post").

This property helps determine the method by which the form is submitted.
1. Get()
2. Post()

GET:

 Appends the form data to the URL, in name/value pairs


 NEVER use GET to send sensitive data! (the submitted form data is visible in the
URL!)
 The length of a URL is limited (2048 characters)
 Useful for form submissions where a user wants to bookmark the result
 GET is good for non-secure data, like query strings in Google

POST:

 Appends the form data inside the body of the HTTP request (the submitted form
data is not shown in the URL)
 POST has no size limitations, and can be used to send large amounts of data.
 Form submissions with POST cannot be bookmarked
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Target :
The target attribute specifies where to display the response that is received after
submitting the form.

The target attribute can have one of the following values:

Value Description

_blank The response is displayed in a new window or tab

_self The response is displayed in the current window

_parent The response is displayed in the parent frame

_top The response is displayed in the full body of the window

framename The response is displayed in a named iframe

The default value is _self which means that the response will open in the current
window.

elements[]:
elements property of form object is an array used to access any element of the
CSS[22519]
form. It contains all fields
MR.SWAMI and controls
R.S.{MOBILE present in the
NO:-+91-8275265361] form. The user can access
any element associated with the form by using the looping concept on the
elements array.

encoding:
The encoding property of a form object is used to access the enctype attribute
present in HTML associated with the <form> tag. This property is a read or write
property and its value is a string. This property helps determine the way of
encoding the form data.

length:
length property of form object is used to specify the number of elements in
the form. This denotes the length of the elements array associated with the
form.
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

button:
The button property of form object denotes the button GUI control placed in the
form.

checkbox:
checkbox property of form object denotes the checkbox field placed in the form.

FileUpload:
FileUpload property of form object denotes the file upload field placed in the form..

hidden:
The hidden property of form object denotes the hidden field placed in the form.

password:
password property of form object denotes the object that is placed as a
password field in the form.

radio:
radio property of form object denotes the radio button field placed in the form.

reset:
As the name implies, the reset property of form object denotes the object placed
as reset button in the form.

select:
select property of form object denotes the selection list object placed in the form.
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

submit:
submit property of form object denotes the submit button field that is placed in the
form.

text:
text property of form object denotes the text field placed in the form.

textarea:
textarea property of form object denotes the text area field placed in the form.

An example to understand the above explanations in detail:

<FORM NAME="exforsys" ACTION="" METHOD="GET">


Input Values:<BR>
<INPUT TYPE="text" NAME="test" VALUE=""><P>
<INPUT TYPE="button" NAME="example"
VALUE="Click"onClick="testfunc(this.form)">
</FORM>

Here the FORM NAME="exforsys" creates and denotes the name of the form. The
user can refer
to the form in his or her code of JavaScript by the name exforsys. The form
name given must follow the naming conventions or rules of JavaScript’s
variable or function naming rules. The
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

next word, ACTION="" tells the way the user wants the browser to handle the
form when it is submitted to a CGI program running on the server. It can also be
left as not specified with any of the above properties. This means the URL for the
CGI program is then omitted.

The METHOD="GET" defines that the method data is passed to the server
when the form is submitted.

INPUT TYPE="text" defines the object used as a text box with the name of the
text box as a test with no initial value specified. INPUT TYPE="button" defines
the object used as a button with the name of the button object as an example. The
value is specified as Click and when the button is clicked, the onClick event
handler fires and the function associated with it (testfunc(this.form)) is called.

Methods of form object:


 reset()
 submit()
 handleEvent()
reset():
reset() method of form object is used to reset a form.

submit():
submit() method of form object is used to submit a form.

handleEvent():
handleEvent() method of form object is used to start or invoke a form’s event
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

handler for a specified event.

Hidden Object

 Hidden object represents a hidden input field in an HTML form and it is invisible to
the user.

 This object can be placed anywhere on the web page.

 It is used to send hidden form of data to a server.


Syntax:
<input type= “hidden”>

Hidden Object Properties

Propert Descriptio
y n
Name It sets and returns the value of the name attribute of the hidden input
field.
Type It returns type of a form element.
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Value It sets or returns the value of the value attribute of the hidden input field.

3. Password Object

 Password object represents a single-line password field in an HTML form.


 The content of a password field will be masked – appears as spots or asterisks
in the browser using password object.
Syntax:
<input type= “password”>

Password Object Properties

Property Descriptio
n

defaultValu It sets or returns the default value of a password field.


e

maxLength It sets or returns the maximum number of characters allowed in a


password filed.

Name It sets or returns the value of the name attribute of a password field.

readOnly It sets or returns whether a password fields is read only or not.

Size It sets or returns the width of a password field.


CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Value It sets or returns the value of the attribute of the password field.

Password Object Methods

Method Descriptio
n

select() It selects the content of a password field.

4. Checkbox Object

 Check box object represents a checkbox in an HTML form.


CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

 It allows the user to select one or more options from the available choices.
Syntax:
<input type= ―checkbox‖>

Checkbox Object Properties

Property Descriptio
n
Name It sets or returns the name of the checkbox.

Type It returns the value ―check‖.

Value It sets or returns the value of the attribute of a checkbox.

checked It sets or returns the checked state of a checkbox.

defaultChecked It returns the default value of the checked attribute.

Checkbox Object Methods

Method Descriptio
n

click() It sets the checked property.

5. Select Object
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

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

Select Object Collections

Collection Descriptio
n
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

options It returns a collection of all the options in a dropdown list.

Select Object Properties

Property Descriptio
n

Length It returns the number of options in a dropdown list.

selectedIndex It sets or returns the index of the selected option in a dropdown list.

Type It returns a type of form element.

name It returns the name of the selection list.

Select Object Methods

Method Descripti
on

add() It adds an option to a dropdown list.

remove() It removes an option from a dropdown list.

6. Option Object
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

 Option object represents an HTML <option> element.

 It is used to add items to a select element.


Syntax:
<option value> . . . </option>

Option Object Properties

Property Descriptio
n
Index It sets or returns the index position of an option in a dropdown list.
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Text It sets or returns the text of an option element.

defaultSelected It determines whether the option is selected by default.

Value It sets or returns the value to the server if the option was selected.

Prototype It is used to create additional properties.

Option Object Methods

Methods Descripti
on

blur() It removes the focus from the option.

focus() It gives the focus to the option.

Example : Simple Program on Option Object Method

<html>

<head>

<script
type="text/javascript">
function
optionfruit(select)
{
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

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>");

}
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

</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:
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Your Favorite Fruit is Mango.

7. Radio Object

Radio object represents a radio button in an HTML form.

Syntax:
<input type= ―radio‖>
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Radio Object Properties

Property Descriptio
n

Checked It sets or returns the checked state of a radio button.

defaultChecked Returns the default value of the checked attribute.

Name It sets or returns the value of the name attribute of a radio button.

Type It returns the type of element which is radio button.

Value It sets or returns the value of the radio button.

Radio Object Methods

Method Descriptio
n

blur() It takes the focus away from the radio button.

click() It acts as if the user clicked the button.

focus() It gives the focus to the radio button.

8. Text Object

Text object represents a single-line text input field in an HTML form.


CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Syntax:
<input type= ―text‖>

Text Object Properties

Property Descriptio
n
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Value It sets or returns the value of the text field.

defaultValu It sets or returns the default value of a text field.


e
Name It sets or returns the value of the name attribute of a text field.

maxLength It sets or returns the maximum number of characters allowed in a text


field.

readOnly It sets or returns whether a text field is read-only or not.

Size It sets or returns the width of a text field.

Type It returns type of form element of a text field.

9. Textarea Object

Textarea object represents a text-area in an HTML form.

Syntax:
<textarea> . . . </textarea>

Textarea Object Properties

Property Descriptio
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Value It sets or returns the value of the text field.

defaultValue It sets or returns the default value of a text field.

Name It sets or returns the value of the name attribute of a text field.

Type It returns type of form element of a text field.

Rows It displays the number of rows in a text area.

Cols It displays the number of columns in a text area.


CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

https://www.tutorialride.com/javascript/javascript-dom-frame-object.htm

JavaScript Events

In this tutorial you will learn how to handle events in JavaScript.

Understanding Events and Event Handlers

An event is something that happens when user interact with the web page, such as
when he clicked a link or button, entered text into an input box or textarea, made
selection in a select box, pressed key on the keyboard, moved the mouse pointer,
submits a form, etc. In some cases, the Browser itself can trigger the events, such
as the page load and unload events.

When an event occur, you can use a JavaScript event handler (or an event listener)
to detect them and perform specific task or set of tasks. By convention, the names
for event handlers always begin with the word "on", so an event handler for the
click event is called onclick, similarly an event handler for the load event is called
onload, event handler for the blur event is called onblur, and so on.

There are several ways to assign an event handler. The simplest way is to add
them directly to the start tag of the HTML elements using the special event-
handler attributes. For example, to assign a click handler for a button element,
we can use onclick attribute, like this:
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Example
Try this code »

<button type="button" onclick="alert('Hello World!')">Click Me</button>


However, to keep the JavaScript seperate from HTML, you can set up the event
handler in an external JavaScript file or within the <script> and </script> tags,
like this:

Example
Try this code »

<button type="button" id="myBtn">Click Me</button>


<script>
function sayHello()
{ alert('Hello
World!');
}
document.getElementById("myBtn").onclick = sayHello;

Note: Since HTML attributes are case-insensitive so onclick may also be written
as onClick, OnClick or ONCLICK. But its value is case-sensitive.

</script>
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

In general, the events can be categorized into four main groups — mouse
events, keyboard events, form events and document/window events. There are
many other events, we will learn about them in later chapters. The following
section will give you a brief overview of the most useful events one by one
along with the real life practice examples.

Mouse Events

A mouse event is triggered when the user click some element, move the mouse
pointer over an element, etc. Here're some most important mouse events and
their event handler.

The Click Event (onclick)

The click event occurs when a user clicks on an element on a web page. Often,
these are form elements and links. You can handle a click event with an onclick
event handler.

The following example will show you an alert message when you click on the
elements.

Example
Try this code »

<button type="button" onclick="alert('You have clicked a button!');">Click


Me</button>
<a href="#" onclick="alert('You have clicked a link!');">Click Me</a>
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

The Contextmenu Event (oncontextmenu)

The contextmenu event occurs when a user clicks the right mouse button on an
element to open a context menu. You can handle a contextmenu event with an
oncontextmenu event handler.

The following example will show an alert message when you right-click on the
elements.

Example
Try this code »

<button type="button" oncontextmenu="alert('You have right-clicked a


button!');">Right Click
on Me</button>
<a href="#" oncontextmenu="alert('You have right-clicked a link!');">Right Click on
Me</a>

The Mouseover Event (onmouseover)

The mouseover event occurs when a user moves the mouse pointer over an element.

You can handle the mouseover event with the onmouseover event handler.
The following example will show you an alert message when you place
mouse over the elements.

Example
Try this code »
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

<button type="button" onmouseover="alert('You have placed mouse


pointer over a button!');">Place Mouse Over Me</button>
<a href="#" onmouseover="alert('You have placed mouse pointer over a
link!');">Place Mouse Over Me</a>

The Mouseout Event (onmouseout)

The mouseout event occurs when a user moves the mouse pointer outside of an
element.

You can handle the mouseout event with the onmouseout event handler. The
following example will show you an alert message when the mouseout event
occurs.

Example
Try this code »

<button type="button" onmouseout="alert('You have moved out of the


button!');">Place Mouse
Inside Me and Move Out</button>
<a href="#" onmouseout="alert('You have moved out of the link!');">Place
Mouse Inside Me and Move Out</a>
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Keyboard Events

A keyboard event is fired when the user press or release a key on the keyboard.
Here're some most important keyboard events and their event handler.

The Keydown Event (onkeydown)

The keydown event occurs when the user presses down a key on the keyboard.

You can handle the keydown event with the onkeydown event handler. The
following example will show you an alert message when the keydown event
occurs.

Example
Try this code »

<input type="text" onkeydown="alert('You have pressed a key inside text input!')">


<textarea onkeydown="alert('You have pressed a key inside textarea!')"></textarea>

The Keyup Event (onkeyup)

The keyup event occurs when the user releases a key on the keyboard.

You can handle the keyup event with the onkeyup event handler. The following
example will show you an alert message when the keyup event occurs.
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Example
Try this code »

<input type="text" onkeyup="alert('You have released a key inside text input!')">


<textarea onkeyup="alert('You have released a key inside textarea!')"></textarea>

The Keypress Event (onkeypress)

The keypress event occurs when a user presses down a key on the keyboard that
has a character value associated with it. For example, keys like Ctrl, Shift, Alt,
Esc, Arrow keys, etc. will not generate a keypress event, but will generate a
keydown and keyup event.

You can handle the keypress event with the onkeypress event handler. The
following example will show you an alert message when the keypress event
occurs.

Example
Try this code »

<input type="text" onkeypress="alert('You have pressed a key inside text input!')">


<textarea onkeypress="alert('You have pressed a key inside textarea!')"></textarea>
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Form Events

A form event is fired when a form control receive or loses focus or when the user
modify a form control value such as by typing text in a text input, select any
option in a select box etc. Here're some most important form events and their
event handler.

The Focus Event (onfocus)

The focus event occurs when the user gives focus to an element on a web page.

You can handle the focus event with the onfocus event handler. The following
example will highlight the background of text input in yellow color when it
receives the focus.

Example
Try this code »

<script>
function highlightInput(elm){
elm.style.background =
"yellow";
}
</script>
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

<input type="text" onfocus="highlightInput(this)">

Note: The value of this keyword inside an event handler refers to the element which has the
handler on it (i.e. where the event is currently being delivered).

<button type="button">Button</button>

The Blur Event (onblur)

The blur event occurs when the user takes the focus away from a form element or a
window.

You can handle the blur event with the onblur event handler. The following
example will show you an alert message when the text input element loses focus.

Example
Try this code »

<input type="text" onblur="alert('Text input loses focus!')">


<button type="button">Submit</button>
To take the focus away from a form element first click inside of it then press the
tab key on the keyboard, give focus on something else, or click outside of it.

The Change Event (onchange)

The change event occurs when a user changes the value of a form element.

You can handle the change event with the onchange event handler. The following
example will show you an alert message when you change the option in the select
box.
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Example
Try this code »

<select onchange="alert('You have changed the selection!');">


<option>Select</option>
<option>Male</option>
<option>Female</option>
</select>

The Submit Event (onsubmit)

The submit event only occurs when the user submits a form on a web page.

You can handle the submit event with the onsubmit event handler. The following
example will show you an alert message while submitting the form to the server.

Example
Try this code »
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

<form action="action.php" method="post" onsubmit="alert('Form data will be


submitted to the server!');">
<label>First Name:</label>
<input type="text" name="first-name" required>
<input type="submit" value="Submit">
</form>

Document/Window Events

Events are also triggered in situations when the page has loaded or when user
resize the browser window, etc. Here're some most important document/window
events and their event handler.

The Load Event (onload)

The load event occurs when a web page has finished loading in the web browser.

You can handle the load event with the onload event handler. The following
example will show you an alert message as soon as the page finishes loading.

Example
Try this code »
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

<body onload="window.alert('Page is loaded successfully!');">


<h1>This is a heading</h1>
<p>This is paragraph of text.</p>
</body>

The Unload Event (onunload)

The unload event occurs when a user leaves the current web page.

You can handle the unload event with the onunload event handler. The following
example will show you an alert message when you try to leave the page.

Example
Try this code »

<body onunload="alert('Are you sure you want to leave this page?');">


<h1>This is a heading</h1>
<p>This is paragraph of text.</p>
</body>
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

The Resize Event (onresize)

The resize event occurs when a user resizes the browser window. The resize event
also occurs in situations when the browser window is minimized or maximized.

You can handle the resize event with the onresize event handler. The following
example will show you an alert message when you resize the browser window
to a new width and height.

Example
Try this code »

<p id="result"></p>
<script>
function
displayWindowSize() {
var w =
window.outerWidth; var
h = window.outerHeight;
var txt = "Window size: width=" + w + ",
height=" + h;
document.getElementById("result").innerHTM
L = txt;
}
window.onresize = displayWindowSize;
</script>
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

https://www.tutorialrepublic.com/javascript-tutorial/javascript-events.php

<!DOCTYPE html>

<html>

<body>

<form>

<select id="mySelect" size="8">

<option>Apple</option>

<option>Pear</option>

<option>Banana</option>

<option>Orange</option>

</select>
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

</form>

<br>

<p>Click the button to add a "Kiwi" option at the end of the dropdown list.</p>

<button type="button" onclick="myFunction()">Insert option</button>

********************************************************************
**********

<script>

function myFunction() {

var x =
document.getElementById("mySelect");
var option =
document.createElement("option");
option.text = prompt("Enter the Student
Name="); x.add(option);
}

</script>
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

</body>

</html>

function getOption(){

var select = document.getElementById("dynamic-


select"); if(select.options.length > 0) {
var option = select.options[select.selectedIndex];
alert("Text: " + option.text + "\nValue: " +
option.value);
} else {

window.alert("Select box is empty");


CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

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");
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

select.options.length = 0;
}

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Dynamically add/remove options select - JavaScript</title>

</head>

<body>
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

<select id="dynamic-select">

<option value="1">one</option>

<option value="2">two</option>

<option value="3">three</option>

</select>

<button onclick="getOption()">get item</button>

<button onclick="addOption()">add item</button>

<button onclick="removeOption()">remove item</button>

<button onclick="removeAllOptions()">remove all</button>

<script src="script.js"></script>

</body>

</html>

You might also like