0% found this document useful (0 votes)
37 views32 pages

JS Events Nad Onwards

Uploaded by

Tanusha hande
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views32 pages

JS Events Nad Onwards

Uploaded by

Tanusha hande
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

https://www.tutorialride.

com/javascript

Introduction to Event Handling

 Event Handling is a software routine that processes actions, such as keystrokes and mouse
movements.
 It is the receipt of an event at some event handler from an event producer and subsequent
processes.

Functions of Event Handling

 Event Handling identifies where an event should be forwarded.


 It makes the forward event.
 It receives the forwarded event.
 It takes some kind of appropriate action in response, such as writing to a log, sending an error or
recovery routine or sending a message.
 The event handler may ultimately forward the event to an event consumer.

Event Handlers
Event Handler Description

onAbort It executes when the user aborts loading an image.

onBlur It executes when the input focus leaves the field of a text, textarea or a select option.

onChange It executes when the input focus exits the field after the user modifies its text.

In this, a function is called when an object in a button is clicked, a link is pushed, a


onClick
checkbox is checked or an image map is selected. It can return false to cancel the action.

onError It executes when an error occurs while loading a document or an image.

It executes when input focus enters the field by tabbing in or by clicking but not selecting
onFocus
input from the field.

onLoad It executes when a window or image finishes loading.

onMouseOver The JavaScript code is called when the mouse is placed over a specific link or an object.

onMouseOut The JavaScript code is called when the mouse leaves a specific link or an object.

onReset It executes when the user resets a form by clicking on the reset button.

onSelect It executes when the user selects some of the text within a text or textarea field.

onSubmit It calls when the form is submitted.

onUnload It calls when a document is exited.


Example : Simple Program on onload() Event handler

<html>
<head>
<script type="text/javascript">
function time()
{
var d = new Date();
var ty = d.getHours() + ":"+d.getMinutes()+":"+d.getSeconds();
document.frmty.timetxt.value=ty;
setInterval("time()",1000)
}
</script>
</head>
<body onload="time()">
<center><h2>Displaying Time</h2>
<form name="frmty">
<input type=text name=timetxt size="8">
</form>
</center>
</body>
</html>

Output:

Example: Simple Program on onsubmit() & onfocus() Event handler

<html>
<body>
<script>
function validateform()
{
var uname=document.myform.name.value;
var upassword=document.myform.password.value;
if (uname==null || uname=="")
{
alert("Name cannot be left blank");
return false;
}
else if(upassword.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
}
function emailvalidation()
{
var a=document.myform.email.value
if (a.indexOf("@")==-1)
{
alert("Please enter valid email address")
document.myform.email.focus()
}
}
</script>
<body>
<form name="myform" method="post" action="validpage.html" onsubmit="return
validateform()">
Email: <input type="text" size="20" name="email" onblur="emailvalidation()"><br>
User Name: <input type="text" name="name"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Submit" >
</form>
</body>
</html>

validpage.html //File name

<html>
<body>
<script type="text/javascript">
alert("You are a Valid User !!!");
</script>
</body>
</html>

Output:
Introduction to Arrays

 Array is a grouping of objects.


 It stores multiple values in a single variable.
 It stores a fixed-size sequential collection of elements of the same type.
 It is used to store collection of data.

Creating and Initializing Arrays


var variable_name = new Array(); // Creating an Array
var arr = []; // Creating an Array
var arr1 = [1, 2, 3]; // Initializing an Array

Multidimensional Array
var arr2 = [
[1, 2, 3] ,
['a', 'b', 'c'] ,
['x', 'y', 'z']
];

Iteration through Arrays

function show_array(arr)
{
for (var i = 0; i < arr.length; i++ )
{
document.write(array[i]);
document.write('<br/>');
}
}
var arr1 = [1, 2, 3];
show_array(arr1);

Array Properties
Array Properties Description

Constructor It returns a reference to the array function that created the object.

Index It represents the zero-based index of the match in the string.

Length It reflects the number of elements in an array.

Input It presents only an array created by regular expression matches.

Prototype It allows you to add properties and methods to an object.

Array Methods
Methods Description

concat() It returns a new array comprised of this array joined with other arrays and values.

every() It returns true if every element in this array satisfies the provided testing function.

It creates a new array with all the elements of this array for which the provided filtering
filter()
function returns true.

indexOf() It returns the first index of an element within the array equal to the specified value.

join() It joins all elements of an array into a string.

pop() It removes the last element from an array and returns that element.

push() It adds one or more elements to the end of an array and returns the new length of the array.

reverse() It reverses the order of the elements of an array.

sort() It represents the source code of an object.

Example: Program on Array Methods – POP() & PUSH()

<html>
<body>
<button onclick="arrpop();">POP</button>
<button onclick="arrpush();"> PUSH </button>
<script>
function arrpop()
{
var numbers = ["1", "2", "3", "4", "5", "ABC"];
document.write(numbers.pop()+" "+"Removed"+"<br>");
//pop() removes the last element of an array

// Now we have [1,2,3,4,5]


document.write("Now length is: "+numbers.length); // ABC removed
}
function arrpush()
{
var numbers = ["1","2","3","4","5","6"]
numbers.push("7");
// now we got ["1","2","3","4","5","6"]
document.write("Added element is :"+" "+numbers[numbers.length-1])
// Now we have [1,2,3,4,5,6]
document.write("<br>"+"Now length is: "+numbers.length); // 7 Added
}
</script>
</body>
</html>

Output:

Built-in Objects

 Built-in objects are not related to any Window or DOM object model.
 These objects are used for simple data processing in the JavaScript.

1. Math Object

 Math object is a built-in static object.


 It is used for performing complex math operations.

Math Properties
Math Property Description

SQRT2 Returns square root of 2.

PI Returns Π value.

E\ Returns Euler's Constant.

LN2 Returns natural logarithm of 2.

LN10 Returns natural logarithm of 10.

LOG2E Returns base 2 logarithm of E.

LOG10E Returns 10 logarithm of E.

Math Methods

Methods Description

abs() Returns the absolute value of a number.

acos() Returns the arccosine (in radians) of a number.

ceil() Returns the smallest integer greater than or equal to a number.

cos() Returns cosine of a number.

floor() Returns the largest integer less than or equal to a number.

log() Returns the natural logarithm (base E) of a number.

max() Returns the largest of zero or more numbers.

min() Returns the smallest of zero or more numbers.

pow() Returns base to the exponent power, that is base exponent.

Example: Simple Program on Math Object Methods

<html>
<head>
<title>JavaScript Math Object Methods</title>
</head>
<body>
<script type="text/javascript">

var value = Math.abs(20);


document.write("ABS Test Value : " + value +"<br>");

var value = Math.acos(-1);


document.write("ACOS Test Value : " + value +"<br>");

var value = Math.asin(1);


document.write("ASIN Test Value : " + value +"<br>");

var value = Math.atan(.5);


document.write("ATAN Test Value : " + value +"<br>");
</script>
</body>
</html>

Output

ABS Test Value : 20


ACOS Test Value : 3.141592653589793
ASIN Test Value : 1.5707963267948966
ATAN Test Value : 0.4636476090008061

Example: Simple Program on Math Object Properties

<html>
<head>
<title>JavaScript Math Object Properties</title>
</head>
<body>
<script type="text/javascript">
var value1 = Math.E
document.write("E Value is :" + value1 + "<br>");

var value2 = Math.LN2


document.write("LN2 Value is :" + value2 + "<br>");

var value3 = Math.LN10


document.write("LN10 Value is :" + value3 + "<br>");

var value4 = Math.PI


document.write("PI Value is :" + value4 + "<br>");
</script>
</body>
</html>
Output:

E Value is :2.718281828459045
LN2 Value is :0.6931471805599453
LN10 Value is :2.302585092994046
PI Value is :3.141592653589793

2. Date Object

 Date is a data type.


 Date object manipulates date and time.
 Date() constructor takes no arguments.
 Date object allows you to get and set the year, month, day, hour, minute, second and
millisecond fields.

Syntax:
var variable_name = new Date();

Example:
var current_date = new Date();

Date Methods

Methods Description

Date() Returns current date and time.

getDate() Returns the day of the month.

getDay() Returns the day of the week.

getFullYear() Returns the year.

getHours() Returns the hour.

getMinutes() Returns the minutes.

getSeconds() Returns the seconds.

getMilliseconds() Returns the milliseconds.

getTime() Returns the number of milliseconds since January 1, 1970 at 12:00 AM.

getTimezoneOffset() Returns the timezone offset in minutes for the current locale.

getMonth() Returns the month.

setDate() Sets the day of the month.


setFullYear() Sets the full year.

setHours() Sets the hours.

setMinutes() Sets the minutes.

setSeconds() Sets the seconds.

setMilliseconds() Sets the milliseconds.

setTime() Sets the number of milliseconds since January 1, 1970 at 12:00 AM.

setMonth() Sets the month.

toDateString() Returns the date portion of the Date as a human-readable string.

toLocaleString() Returns the Date object as a string.

toGMTString() Returns the Date object as a string in GMT timezone.

valueOf() Returns the primitive value of a Date object.

Example : JavaScript Date() Methods Program

<html>
<body>
<center>
<h2>Date Methods</h2>
<script type="text/javascript">
var d = new Date();
document.write("<b>Locale String:</b> " + d.toLocaleString()+"<br>");
document.write("<b>Hours:</b> " + d.getHours()+"<br>");
document.write("<b>Day:</b> " + d.getDay()+"<br>");
document.write("<b>Month:</b> " + d.getMonth()+"<br>");
document.write("<b>FullYear:</b> " + d.getFullYear()+"<br>");
document.write("<b>Minutes:</b> " + d.getMinutes()+"<br>");
</script>
</center>
</body>
</html>
Output:

3. String Object

 String objects are used to work with text.


 It works with a series of characters.

Syntax:
var variable_name = new String(string);

Example:
var s = new String(string);

String Properties

Properties Description

length It returns the length of the string.

prototype It allows you to add properties and methods to an object.

constructor It returns the reference to the String function that created the object.

String Methods

Methods Description

charAt() It returns the character at the specified index.

charCodeAt() It returns the ASCII code of the character at the specified position.

concat() It combines the text of two strings and returns a new string.

indexOf() It returns the index within the calling String object.

match() It is used to match a regular expression against a string.


replace() It is used to replace the matched substring with a new substring.

search() It executes the search for a match between a regular expression.

slice() It extracts a session of a string and returns a new string.

split() It splits a string object into an array of strings by separating the string into the substrings.

toLowerCase() It returns the calling string value converted lower case.

toUpperCase() Returns the calling string value converted to uppercase.

Example : JavaScript String() Methods Program

<html>
<body>
<center>
<script type="text/javascript">
var str = "CareerRide Info";
var s = str.split();
document.write("<b>Char At:</b> " + str.charAt(1)+"<br>");
document.write("<b>CharCode At:</b> " + str.charCodeAt(2)+"<br>");
document.write("<b>Index of:</b> " + str.indexOf("ide")+"<br>");
document.write("<b>Lower Case:</b> " + str.toLowerCase()+"<br>");
document.write("<b>Upper Case:</b> " + str.toUpperCase()+"<br>");
</script>
<center>
</body>
</html>

Output:

Example : Simple Program on User-defined Function


<html>
<body>
<script type="text/javascript">
function add() // Function Declaration
{
var a = 2,b = 3;
var sum = 0;
sum = a+b;
document.write("<b>Addition: </b>"+sum);
}
</script>
<p> Click the Button</p>
<input type="button" onClick="add()" value="Click"> //add() - Calling Function
</body>
</html>

Output:

Addition: 5

Introducing DOM

 Document Object Model (DOM) is a standard object model and programming interface for
HTML.
 It defines a standard for accessing documents.
 It is a World Wide Consortium standard.
 It is a platform and language-neutral interface that allows programs and scripts to dynamically
access and update the content, structure and style of a document.
1. DOM Object
DOM Properties

Properties Description

Cookie It returns all name or value pairs of cookies in the document.

documentMode It returns the mode used by the browser to render the document.

Domain It returns the domain name of the server that loaded the document.

lastModified It returns the date and time of last modified document.

readyState It returns the status of the document.

Referrer It returns the URL of the document that loaded the current document.

Title It sets or returns the title of the document.

URL It returns the full URL of the document.


DOM Methods

Methods Description

close() It closes the output stream previously opened with document.open().

clear() It clears the document in a window.

getElementById() It accesses the first element with the specified ID.

getElementByName() It accesses all the elements with a specified name.

getElementByTagName() It accesses all elements with a specified tagname.

open() It opens an output stream to collect the output from document.write().

write() It writes output (JavaScript code) to a document.

writeln() Same as write(), but adds a newline character after each statement.

Example : Program on DOM() Methods

<html>
<head>
<script type="text/javascript">
function check()
{
var username = document.getElementById("uname");
var password = document.getElementById("pass");
if(username.value=="abc" && password.value=="123")
alert("Hello!!! You are successfully signed in");
else
alert("Invalid Username and Password!!!");
}
</script>
</head>
<body>
<h2>Login</h2>
Username:<input type = "text" id="uname"><br>
Password:<input type = "password" id="pass"><br>
<input type="button" onClick="check()" Value="Sign In">
</body>
</html>

Output:
2. Element Object
Element object contains references of all elements in a form.

Element Object Properties

Property Description

Id It sets and returns the Id of an element.

Value It returns the value of an element.

It sets or returns the HTML contents of an element.


innerHTML If you want to access the text within a non <input> HTML element, then you have to use
innerHTML property instead of value.
Length It returns the number of entries in the element array.

tagName It returns the tagname of an element as a string in uppercase.

Example : Simple Program on Element Object

<html>
<head>
<script type="text/javascript">
function welcome()
{
var fname = document.getElementById('fname');
var buttxt = document.getElementById('buttxt');
buttxt.innerHTML = fname.value;
}
</script>
</head>
<body>
<p>Welcome <b id = 'buttxt'></b></p>
Your Name : <input type = "text" id="fname"><br>
<input type = "button" onClick="welcome()" value="Enter">
</body>
</html>

Output:

3. Anchor Object

 Anchor object represents an HTML hyperlink.


 It allows you to create a link to another document with the 'href' attribute.
 You can access an anchor by using getElementById() or by searching through the anchors[ ] array
of the Document object.
 You can add anchors to the anchors[ ] array but you cannot delete, replace or modify them.

Anchor Object Properties

Property Description

Href It sets or returns the value of the href attribute of a link.

name It sets or returns the value of the name attribute of a link.

1. Window Object

 Window object is a top-level object in Client-Side JavaScript.


 Window object represents the browser's window.
 It represents an open window in a browser.
 It supports all browsers.
 The document object is a property of the window object. So, typing window.document.write is
same as document.write.
 All global variables are properties and functions are methods of the window object.

Window Object Properties

Property Description

Document It returns the document object for the window (DOM).

Frames It returns an array of all the frames including iframes in the current window.

Closed It returns the boolean value indicating whether a window has been closed or not.

History It returns the history object for the window.

innerHeight It sets or returns the inner height of a window's content area.

innerWidth It sets or returns the inner width of a window's content area.

Length It returns the number of frames in a window.

Location It returns the location object for the window.

Name It sets or returns the name of a window.

Navigator It returns the navigator object for the window.

Opener It returns a reference to the window that created the window.

outerHeight It sets or returns the outer height of a window, including toolbars/scrollbars.

outerWidth It sets or returns the outer width of a window, including toolbars/scrollbars.


Parent It returns the parent window of the current window.

Screen It returns the screen object for the window.

screenX It returns the X coordinate of the window relative to the screen.

screenY It returns the Y coordinate of the window relative to the screen.

Self It returns the current window.

Status It sets the text in the status bar of a window.

Top It returns the topmost browser window that contains frames.

Window Object Method

Method Description

alert() It displays an alert box.

confirm() It displays a dialog box.

prompt() It displays a dialog box that prompts the visitor for input.

setInterval() It calls a function or evaluates an expression at specified intervals.

setTimeout() It evaluates an expression after a specified number of milliseconds.

clearInterval() It clears a timer specified by setInterval().

clearTimeOut() It clears a timer specified by setTimeout().

close() It closes the current window.

open() It opens a new browser window.

createPopup() It creates a pop-up window.

focus() It sets focus to the current window.

blurt() It removes focus from the current window.

moveBy() It moves a window relative to its current position.

moveTo() It moves a window to the specified position.

resizeBy() It resizes the window by the specified pixels.

resizeTo() It resizes the window to the specified width and height.


print() It prints the content of the current window.

scrollBy() It scrolls the content by the specified number of pixels.

scrollTo() It scrolls the content to the specified coordinates.

Example : Simple Program on Window Object

open_window.html //File name

<html>
<head>
<script type="text/javascript">
function openwindow()
{
window.open("welcome.html");
}
</script>
</head>
<body>
<form>
<input type="button" value="Open" onClick=window.alert()>
<input type="button" onClick="openwindow()" value="Open Window">
</form>
</body>
</html>

welcome.html //File name

<html>
<body>
<script type="text/javascript">
{
document.write("<b>Welcome to TutorialRide !!!</b>");
}
</script>
</body>
</html>

Output:
 In the above JavaScript program, when you click on the 'Open Window', you will see the
'welcome.html' opened in another window.
 When you click on the 'Open' button, you will see the alert message box.

2. Navigator Object

 Navigator object is the representation of Internet browser.


 It contains all the information about the visitor's (client) browser.

Navigator Object Properties

Property Description

appName It returns the name of the browser.

appCodeName It returns the code name of the browser.

appVersion It returns the version information of the browser.

cookieEnabled It determines whether cookies are enabled in the browser.

platform It returns which platform the browser is compiled.

userAgent It returns the user agent header sent by the browser to the server.

Navigator Object Methods

Method Description
javaEnabled() It specifies whether or not the browser is Java enabled.

Example : Simple Program on Navigator Object

<html>
<body>
<script type="text/javascript">
document.write("<b>Browser: </b>"+navigator.appName+"<br><br>");
document.write("<b>Browser Version: </b>"+navigator.appVersion+"<br><br>");
document.write("<b>Browser Code: </b>"+navigator.appCodeName+"<br><br>");
document.write("<b>Platform: </b>"+navigator.platform+"<br><br>");
document.write("<b>Cookie Enabled: </b>"+navigator.cookieEnabled+"<br><br>");
document.write("<b>User Agent: </b>"+navigator.userAgent+"<br><br>");
document.write("<b>Java Enabled: </b>"+navigator.javaEnabled()+"<br><br>");
</script>
</body>
</html>

Output:

Browser: Netscape

Browser Version: 5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu
Chromium/37.0.2062.120 Chrome/37.0.2062.120 Safari/537.36

Browser Code: Mozilla

Platform: Linux x86_64

Cookie Enabled: true

User Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu
Chromium/37.0.2062.120 Chrome/37.0.2062.120 Safari/537.36

Java Enabled: true

3. History Object

 History object is a part of the window object.


 It is accessed through the window.history property.
 It contains the information of the URLs visited by the user within a browser window.
History Object Properties

Property Description

Length It returns the number of URLs in the history list.

Current It returns the current document URL.

Next It returns the URL of the next document in the History object.

Previous It returns the URL of the last document in the history object.

History Object Methods

Method Description

back() It loads the previous URL in the history list.

forward() It loads the next URL in the history list.

go(“URL”) It loads a specific URL from the history list.

4. Location Object

 Location object is a part of the window object.


 It is accessed through the 'window.location' property.
 It contains the information about the current URL.

Location Object Properties

Property Description

hash It returns the anchor portion of a URL.

host It returns the hostname and port of a URL.

hostname It returns the hostname of a URL.

href It returns the entire URL.

pathname It returns the path name of a URL.

port It returns the port number the server uses for a URL.

protocol It returns the protocol of a URL.

search It returns the query portion of a URL.

Location Object Methods


Method Description

assign() It loads a new document.

reload() It reloads the current document.

replace() It replaces the current document with a new one.

Example : Simple Program on Location Object

<html>
<body>
<script type="text/javascript">
document.write("<b>Path Name: </b>"+location.pathname+"<br><br>");
document.write("<b>Href: </b>"+location.href+"<br><br>");
document.write("<b>Protocol: </b>"+location.protcol+"<br><br>");
</script>
</body>
</html>

Output:

Path Name: /home/tutorialride2/location_object.html

Href: file:///home/tutorialride2/location_object.html

Protocol: undefined

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

Syntax:
<form> . . . </form>

Form Object Properties

Property Description

Action It sets and returns the value of the action attribute in a form.
enctype It sets and returns the value of the enctype attribute in a form.

Length It returns the number of elements in a form.

Method It sets and returns the value of the method attribute in a form that is GET or POST.

Name It sets and returns the value of the name attribute in a form.

Target It sets and returns the value of the target attribute in a form.

Form Object Methods

Method Description

reset() It resets a form.

submit() It submits a form.

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

Property Description

Name It sets and returns the value of the name attribute of the hidden input field.

Type It returns type of a form element.

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 Description

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

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.

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

Password Object Methods

Method Description

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

4. Checkbox Object

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


 It allows the user to select one or more options from the available choices.

Syntax:
<input type= “checkbox”>

Checkbox Object Properties

Property Description

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 Description

click() It sets the checked property.


5. Select Object

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

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

Select Object Properties

Property Description

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 Description

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

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

6. Option Object

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

Index It sets or returns the index position of an option in a dropdown list.


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 Description

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)
{
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>");
}
}
</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:

Your Favorite Fruit is Mango.

7. Radio Object
Radio object represents a radio button in an HTML form.

Syntax:
<input type= “radio”>

Radio Object Properties

Property Description

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 Description

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.

Syntax:
<input type= “text”>

Text Object Properties

Property Description

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.

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 Description

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.

You might also like