Download as pdf or txt
Download as pdf or txt
You are on page 1of 116

Javascript Basics

What is JavaScript
 Object based (not object oriented) programming
language
 very limited object creation
 a set of pre-defined objects associated with
 HTML document structure
 many HTML tags constitute JS Objects

 Browser functionality
 provides a limited API to Browser functionality
Where did it come from
 Originally called LiveScript at Netscape
 started out to be a server side scripting language for
providing database connectivity and dynamic HTML
generation on Netscape Web Servers
 Netscape decided it would be a good thing for their
browsers and servers to speak the same language so it
got included in Navigator
 Netscape in alliance w/Sun jointly announced the
language and its new name Java Script
 Because of rapid acceptance by the web community
Microsoft forced to include in IE Browser
Browser compatibility
 For the most part Java Script runs the same way in all
popular browsers
 There are a number of areas where there are slight
differences in how Java Script will run
 There will be a separate set of slides addressing these
differences and making your pages browser neutral.
JavaScript…Java ?
 There is no relationship other than the fact that
Java and JavaScript resemble each other (and C++)
syntactically
 JavaScript is pretty much the de-facto standard for
client-side scripting (Internet Explorer also
provides VBScript & JScript)
 In Netscape browsers there is an API (Live
Connect) that allows JavaScript and Java applets
embedded in the same page to communicate.
What can it be used for
 Some pretty amazing things….
 Text animation
 graphic animation
 simple browser based application
 HTML forms submission
 client-side forms data validation (relieving the server of
this task)
 web site navigation
What do I need to get started
 A web browser
 Netscape Navigator 4.x or later
 MS Internet Explorer 3.x or later
 A text Editor
 Wordpad, Notepad
 Vi, Emacs, xemacs
what happens when a browser
loads a website
1. Fetch the HTML page (e.g. index.html)
2. Begin parsing the HTML
3. The parser encounters a <script> tag referencing an
external script file.
4. The browser requests the script file. Meanwhile, the
parser blocks and stops parsing the other HTML on
your page.
5. After some time the script is downloaded and
subsequently executed.
6. The parser continues parsing the rest of the HTML
document.
 Step #4 causes a bad user experience. Your website
basically stops loading until you've downloaded
all scripts. If there's one thing that users hate it's
waiting for a website to load.
 If your website doesn't load within 2
seconds, people will go to another
website.
The modern approach
 Today, browsers support the async and defer attributes
on scripts. These attributes tell the browser it's safe to
continue parsing while the scripts are being
downloaded.
 async
 <script src="path/to/script1.js" async>
 </script>
 <script src="path/to/script2.js" async>
 </script>
 Scripts with the async attribute are executed
asynchronously. This means the script is executed as
soon as it's downloaded, without blocking the browser
in the meantime.
This implies that it's possible to script 2 is downloaded
& executed before script 1.
defer
 <script src="path/to/script1.js" defer>
 </script>
 <script src="path/to/script2.js" defer>
 </script>

 Scripts with the defer attribute are executed in order


(i.e. first script 1, then script 2). This also does not
block the browser.
Process
 Open your text editor
 create a file containing html and Javascript
 save as text file with file type .htm or .html
 open your browser
 click on file, open file
 locate the file you just created
 open file in browser
Putting JavaScript into your HTML
 in an external file
 collect commonly used functions together into external
function libraries on the server
 added benefit of privacy from all but the most curious users
 in-line with your HTML
 as an expression for an HTML tag attribute
 within some HTML tags as Event Handlers
<SCRIPT>…</SCRIPT>
 <SCRIPT language=…. src=……></SCRIPT>
 The <SCRIPT> tag indicates to the browser the
beginning of an embedded script; </SCRIPT>
indicates the end of an embedded script.
 the “language” attribute indicates the script
processor to be used
 the “src” attribute indicates the URL of a file on the
server containing the script to be embedded
Scripts
 Since scripts are placed in line with your HTML older
browsers will attempt to render them as text.
 To preclude this hide them in side of an HTML
comment . <!-- -->
 For commenting your JavaScript use the /*…*/ or //
<SCRIPT>
 <SCRIPT LANGUAGE=“JavaScript”>
 <!-- start hiding code from old browsers>
 Your
 Javascript
 Code
 Goes
 Here
 // Stop Hiding code -->
 </SCRIPT>
Data Types in Java Script

Primitive data types


 a primitive (primitive value, primitive data type) is
data that is not an object and has no methods.
 There are 7 primitive data
types: string, number, bigint, boolean, undefined,
symbol, and null.
 Most of the time, a primitive value is represented
directly at the lowest level of the language
implementation.
 Note: use typeof () function to check the type of
data.
Data Types Cont…
 Non-Primitive
 Object - all properties and methods belonging to
the object or array
 const person = new Object();
 An Object contains Attribute and Behaviour
Variables
 Naming
 start with alpha followed by alphameric (and _)
 Creating
 use the var keyword
 var myName
 definition and initialization can be combined
 Var myName = “Dick”
 var x = 5;
 var y = 10;
 var sum = x + y;
 document.write(sum); // show on browser
 Console.log(sum); //show on console
 O/P: 15
Variable Cont…
 var variables can be re-declared and updated
 var greeter = "hey hi";
 var greeter = "say Hello instead“
 Hoisting of var:
 Hoisting is a JavaScript mechanism where variables
and function declarations are moved to the top of their
scope before code execution.

 Document.write(greeter);
 var greeter = "say hello"
 it is interpreted as this:
 var greeter;
 console.log(greeter); // greeter is undefined
 greeter = "say hello“

 So var variables are hoisted to the top of their scope


and initialized with a value of undefined.
ES6 Features in variables
 const is a new keyword in ES6 for declaring
variables. const is more powerful than var. Once used,
the variable can’t be reassigned. In other words, it’s
an immutable variable except when it used with
objects.
 const a=12;
 a=30; //Not valid
ES6 Features in variables
 Let is now preferred for variable declaration. It's no
surprise as it comes as an improvement
to var declarations. It also solves the problem
with var that we just covered. Let's consider why this is
so
 let greeting = "say Hi";
 let times = 4;
 if (times > 3) {
 let hello = "say Hello instead";
console.log(hello);// "say Hello instead"
 }
 console.log(hello) // hello is not defined

We see that using hello outside its block (the curly braces
where it was defined) returns an error. This is
because let variables are block scoped
 let can be reassigned and take new value. It creates
a mutable variable.
 let is the same as const in that both are blocked-scope.
It means that the variable is only available within its
scope.
JavaScript Operators
 Assignment Operators(=,+=,-=,*=,/=):
 An assignment operator assigns a value to its left
operand based on the value of its right operand. The
basic assignment operator is equal (=), which assigns
the value of its right operand to its left operand. That
is, x = y assigns the value of y to x.
 x += y means x = x + y
 x -= y means x = x - y
 x *= y means x = x * y
 x /= y means x = x / y
 x %= y means x = x % y
 Arithmetic Operators
 Arithmetic operators take numerical values (either
literals or variables) as their operands and return a
single numerical value.
 Standard Arithmetic Operators
 The standard arthmetic operators are addition (+),
subtraction (-), multiplication (*), and division (/).
These operators work in the standard way.
 Modulus (%)
 The modulus operator is used as follows:
var1 % var2
 The modulus operator returns the first operand
modulo the second operand, that is, var1 modulo var2,
in the statement above, where var1 and var2 are
variables. The modulo function is the remainder of
integrally dividing var1 by var2. For example, 12 % 5
returns 2.
 Unary negation (-)
 The unary negation operator must precede its
operand. It negates its operand. For example,
 x = -x
 negates the value of x; that is if x were 3, it would
 Bitwise Logical Operators
 The bitwise logical operators work conceptually as
follows:
 The operands are converted to 32-bit integers, and
expressed a series of bits (zeros and ones).
 Each bit in the first operand is paired with the
corresponding bit in the second operand: first bit to
first bit, second bit to second bit, and so on.
 The operator is applied to each pair of bits, and the
result is constructed bitwise.
 The bitwise operators are:
 Bitwise AND & returns a one if both operands are
ones.
 Bitwise OR | returns a one if either operand is one.
 Bitwise XOR ^ returns a one if one but not both
operands are one.
 For example, the binary representation of 9 is 1001, and
the binary representation of 15 is 1111. So, when the
bitwise operators are applied to these values, the
results are as follows:
 15 & 9 yields 9 (1111 & 1001 = 1001)
 15 | 9 yields 15 (1111 | 1001 = 1111)
 15 ^ 9 yields 6 (1111 ^ 1001 = 0110)
Conditional Statements
 In JavaScript we have three conditional statements:
 if statement - use this statement if you want to
execute a set of code when a condition is true
 if...else statement - use this statement if you want to
select one of two sets of lines to execute
 switch statement - use this statement if you want to
select one of many sets of lines to execute
 If and If...else Statement
 You should use the if statement if you want to execute
some code if a condition is true.
 Syntax
 if (condition) { code to be executed if condition is true }

 Example: next slide


Example
<script type="text/javascript"> Output:
 const a = 7; positive
 let result;
 if (a > 0) {
 result = 'positive';
 } else {
 result = 'NOT positive';
 }
 document.writeln(result);
</script>
 Multiple if...else statements can be nested to create
an else if clause. Note that there is no elseif (in one
word) keyword in JavaScript.
 if (condition1) statement1
 else if (condition2) statement2
 else if (condition3) statement3 ...
 else statementN
 Example:
 let x=20;
if (x > 50)
 { /* do something */ }
 else if (x > 5) { /* do something */ }
 else { /* do something */ }
 Switch Statement
 You should use the Switch statement if you want to
select one of many blocks of code to be executed.
 Syntax
 switch (expression)
{
 case label1: code to be executed if expression = label1
break
 case label2: code to be executed if expression = label2
break
 default: code to be executed if expression is different
from both label1 and label2
 /You will receive a different greeting based //on what
day it is. Note that Sunday=0, //Monday=1, Tuesday=2,
etc.
 <script type="text/javascript">
 var a=6;
 switch (a)
 { case 5: document.write("Finally Friday") break
 case 6: document.write("Super Saturday") break
 case 0: document.write("Sleepy Sunday") break
default: document.write("I'm looking forward to this
weekend!") } </script>
 Output: Super Saturday
Multi-case : chained operations
 var foo = 1;
 var output = 'Output: '; case 5: output += '!';
 switch (foo) console.log(output);
break;
 { case 0: output += 'So ';
default:
 case 1: output += 'What '; console.log('Please pick
 output += 'Is '; a number from 0 to 5!');
 case 2: output += 'Your '; }

 case 3: output += 'Name';


 case 4: output += '?';
console.log(output); break;
 const action = 'say_hello';
 switch (action)
{
 case 'say_hello': let message = 'hello';
console.log(message); break;
 case 'say_hi': let message = 'hi'; console.log(message);
break;
 default: console.log('Empty action received.');
 break;
}
Output: ??
 Ternary Operator
 JavaScript also contains a conditional operator that
assigns a value to a variable based on some condition.
 Syntax
 variablename=(condition)?value1:value2
 Example
 greeting=(visitor=="PRES")?"Dear President ":"Dear “
 If the variable visitor is equal to PRES, then put the
string "Dear President " in the variable named
greeting. If the variable visitor is not equal to PRES,
then put the string "Dear " into the variable named
greeting.
Code:
 let i=12,j=23,k=34;

 const result=(i>j & i>k)?x:(j>k)?j:k;


 console.log("Result:"+result);
Looping
 Looping
 Very often when you write code, you want the same
block of code to run a number of times. You can use
looping statements in your code to do this.
 In JavaScript we have the following looping
statements:
 while - loops through a block of code while a
condition is true
 do...while - loops through a block of code once, and
then repeats the loop while a condition is true
 for - run statements a specified number of times
For Loop
 The for statement will execute a block of code a
specified number of times
 for (initialization; condition; increment)
{ code to be executed }
 do...while
 The do...while statement will execute a block of code
once, and then it will repeat the loop while a condition
is true
 do { code to be executed } while (condition)
 The while statement will execute a block of code while
a condition is true..
 While
 (condition) { code to be executed }
 For Loop Example:
 <html>
<body>
<script type>
for (i=0; i<=5; i++)
{
document.write("<b>The number is " + i + "</b>")
document.write("<br>")
}
</script>
Output: The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
 Do-While Loop Example
 <html>
<body>
<script type="text/javascript">

var i = 0;
 do {
 i++;
 document.writeln("i=" + i + "<br>");

 } while (i <= 5);

</script>
Outputi=1
i=2
i=3
i=4
i=5
i=6
 While Loop Example

<script type="text/javascript">
var i = 0;
 while (i <= 5) {
 i++;
 document.writeln("i=" + i + "<br>");

 };
</script>
Output:i=1
i=2
i=3
i=4
i=5
i=6
Label
 The labeled statement can be used with break or
continue statements. It is prefixing a statement with
an identifier which you can refer to.
O/P: ??
User Input
 The prompt() method displays a dialog box that
prompts the visitor for input.
 A prompt box is often used if you want the user to
input a value before entering a page.

 Example:
 var name=prompt(“Enter Your Name”);
 Document.writeln(“Hello ”+name);
 while (1) {
 var n = prompt("Please enter a number in the range
0…100");
 if (n>=0 && n<=100) break;
 document.writeln(n +" is out of range. Try again.");
 }
 Output:
Arrays
 The Array object, as with arrays in other programming
languages, enables storing a collection of multiple
items under a single variable name, and has members
for performing common array operations.
 let vegetables = []; // blank array
 let fruits = ["Mango", "Apple", "Banana"];// assigned
elements
 Console.log(fruits) O/P:
Arrays
One dimensional arrays
 var myarray = new Array( )

 let arrayObject = new Array();


 console.log(arrayObject);

 var myarray1 = new Array(10) //[<10 empty items>]

var myarray2 = new Array(2,4,6) // 3 elements initialized


to 2, 4, and 6 respectively
 O/P: [2,5,6]
Elements

 We can access array elements by using index value of


the stored data elements. Ever data element stored in
an array is stored at an index. The array index starts
from 0 and goes upto the value (Array.length - 1)

 let arrayObject = new Array(2,5,6,4,7,8,10,34);


 console.log(arrayObject);
 for (let i = 0; i < arrayObject.length; i++) {

 console.log(+i+"")
 }


Array Function
 array.concat() method
 var arr1 = ['Batman', 'Robin'];
 var arr2 = ['Joker', 'Bane'];
 var comp = arr1.concat(arr2);
 console.log(comp);
array.slice() method

array.slice() creates a new array, without mutating the


original one
 let names = ['Batman', 'Catwoman', 'Joker', 'Bane',
'superman', 'angryman'];
 let heroes = names.slice(0, 2);
 console.log(heroes); // [ 'Batman', 'Catwoman' ]

 console.log(names.slice(2)); // starting from index 2 till


end

 console.log(names.slice(2, 4)); //
 console.log(names.slice(1, 5)); //
 console.log(names.slice(-2)); //
 console.log(names.slice(2, -1)); //
array.includes() method
 array.includes(itemToSearch[, fromIndex]) returns a
boolean whether array contains itemToSearch. The
optional argument fromIndex, defaulting to 0,
indicates the index to start searching.
 onst numbers = [1, 2, 3, 4, 5];
 numbers.includes(2); // => true
numbers.includes(99); // => false

 let names = ['Batman', 'Catwoman', 'Joker', 'Bane',


'superman', 'angryman'];
 console.log(names.includes('Catwoman'));
 array.indexOf() method
 const names = ['Batman', 'Catwoman', 'Joker', 'Bane'];
const index = names.indexOf('Joker');
 index; // => 2
array.push() method
 array.push(item1[..., itemN]) method appends one or
more items to the end of an array, returning the new
length.
 const names = ['Batman'];
 names.push('Joker’);
 let names = ['Batman', 'Catwoman', 'Joker', 'Bane',
'superman', 'angryman'];
 names.push(2,5,10);
 console.log(names);
 array.pop() method
 array.pop() method removes the last item from an
array, then returns that item.
 const colors = ['blue', 'green', 'black'];
 const lastColor = colors.pop();
 lastColor; // => 'black'
 colors; // => ['blue', 'green']
 let names = ['Batman', 'Catwoman', 'Joker', 'Bane',
'superman', 'angryman'];
 names.pop();
 console.log(names);
 array.shift() method
 array.shift() method removes the first item from an
array, then returns that item.
 For example, let’s remove the first element
of colors array:
 const colors = ['blue', 'green', 'black'];
 const firstColor = colors.shift();
 firstColor; // => 'blue’
 colors; // => ['green', 'black']
 let names = ['Batman', 'Catwoman', 'Joker', 'Bane',
'superman', 'angryman'];
 names.shift();
 console.log(names);
 array.splice() method

 The splice() method changes the contents of an array


by removing or replacing existing elements and/or
adding new elements in place.
 splice(start)
 splice(start, deleteCount)
 splice(start, deleteCount, item1)
 splice(start, deleteCount, item1, item2, itemN)
 let names = ['Batman', 'Catwoman', 'Joker', 'Bane',
'superman', 'angryman'];
 //names.splice(1); // start from index 1
 names.splice(1, 2); // strat removing from index 1 and remove
2 elements
 names.splice(1, 2, 'Alien', 'Human'); // start removing
from 1 index, delete 2 elements when element replace 2
elements by Alien and Human
 console.log(names);
 Last statement O/P:
 array.sort() method
 array.sort([compare]) method sorts the items of the
array. When the compare function is omitted, the
method converts the items to strings, then orders
them ascending by UTF-16 code units values.

 Sample Code:
 let names = ['Batman', 'Catwoman', 'Joker', 'Bane',
'Superman', 'Angryman'];
 names.sort();
 console.log(names);
 O/P:
 Using Comparator in sort:

 Ascending Order of elemnts:


 let names = [34,4,12,0,-34,56,120];
 names.sort((a,b)=>a-b); // Arrow Function
 console.log(names);

 Descending Order of elements:

 let names = [34,4,12,0,-34,56,120];


 names.sort((a,b)=>b-a);
 console.log(names);
User defined objects
 Implemented as associative arrays
 var point = new Object() // empty object
 point.x = 5 ; point.y = 3; // no longer empty
var anotherpoint = new Object( )
 anotherpoint = newpoint //object assignment
User defined functions
 Function definition:
 function sum() {
 let x=4, y=3
 return x+ y;
}

 a function assigned to a property of an object is


called a method of the object
 within the body of a function arguments[] contains
an array of the arguments
Parametric function
Returning a function
Passing array in function
parameter
Arrow Function
 An arrow function expression is a compact alternative
to a traditional function expression.
 param => expression
(param) => expression
(param1, paramN) => expression
param => {
 statements
 }
(param1, paramN) => { statements}
Built-in objects
 Many commonly used functions are built into the
language for:
 String
 Math
 Array
Math Object
 All the properties and methods ofand can be called by
using Math as an obj Math are static ect without
creating it.
 abs(): Returns the absolute value of a number
 cos()Returns the 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.

random()Returns a pseudo-random number between
0 and 1.
 sqrt()Returns the square root of a number.
Spread syntax
 Spread syntax (...)
 The spread (...) syntax allows an iterable, such as an
array or string, to be expanded in places where zero or
more arguments (for function calls) or elements (for
array literals) are expected.
Max/Min of array using spread
 const arr = [2, 4, 5, 7, 8, 0, 12,
4];
 console.log(Math.max(...arr)); //
spread
 O/P:12
 console.log(Math.min(...arr)); // spread
 O/P:0
String Object
 The String object lets you work with a series of
characters; it wraps Javascript's string primitive data
type with a number of helper methods.
 var val = new String(string);
 Methods:
 charAt()Returns the character at the specified index.
 concat()Combines the text of two strings and returns a
new string.
 indexOf()Returns the index within the calling String
object of the first occurrence of the specified value, or
-1 if not found.

slice()Extracts a section of a string and returns a new
string.
 split()Splits a String object into an array of strings by
separating the string into substrings.

substr()Returns the characters in a string beginning at
the specified location through the specified number of
characters
 toLowerCase()Returns the calling string value
converted to lower case.
 toString()Returns a string representing the specified
object.
Object Based not Object Oriented
 Javascript treats the browser’s objects as a pre-defined
set of objects to which Javascript provides an API.
 Javascript, in addition to being a programming
language, is meant to be a way to program a user’s
browser
Object Hierarchy
window

history document location toolbar

link anchor layer form applet image area

text radio button fileUpload select

textarea checkbox reset option

password submit
Objects
 window - the current browser window
 window.history - the Netscape history list
 window.history.back-move to back page if available
 window.document - the html document currently in the browser client
area
 history.length- property can be used to get the number of pages in the
session history of the browser for the current window.
 window.document.form - a named form or the default form
A few examples...
 window.location = “http://www.yahoo.com”
 will take you to the specified URL (like a goto)
 window.history.back()
 back( ) is a method on history
 will be like clicking the back button in Nav 3
 in Nav 4 will take you back to prev window
 window.history.go(1)
 takes you back to first URL in history array
 window.history.forward();- one step forward
More Example
 window.history.go(-2); // Go back two pages
window.history.go(-1); // Go back one page
window.history.go(0); // Reload the current page
window.history.go(1); // Go forward one page
window.history.go(2); // Go forward two pages
The Object Model
 It is very important to understand the object model
 each object has its own properties, some of which are
read only some of which you can be set directly by
assignment (as location)
 each object also has a set of behaviors called methods
Object Event Handlers
 Most of the objects that make up the Document Object Model
respond to asynchronous, user generated events through
predefined event handlers that handle the event and transfer
control to a user provided event handling function
 Each object has particular events that they will respond to
 the way you specify an event handler is by adding an additional
attribute to the HTML tag that specifies the event and the
particular handler
 <input name=bt1 type=button value=ok onClick=“acb( );”>
 if the button is click the function abc( ) will be run
Alert
The “Alert” function is useful in user notification and debugging of
Javascripts.

Pops up a message in a pop-up dialog box

Ex, alert(“help, help, help”);


Events
 onAbort
 onChange
 onClick
 onError
 onFocus
 onLoad
 onMouseOut
 onMouseOver
 onReset
 onSelect
 onSubmit
 onUnload
onAbort
 Activated when a user aborts the loading of an image

<img name=ball src=images/ball.gif onAbort=“alert(‘You missed a nice picture’)”>


onChange
 Used with select, text and textarea objects
 use instead of onBlur to validate only if a value has
changed
onClick
 Used with button, checkbox,link, radio, reset, and
submit objects.

<input type=button name=btn1 value=“Click Me” onClick=“alert(‘button was clicked’;” >


onError
 Used with image and window objects to invoke a
handler if an error occurs while an image or window is
loading.
 Setting window.onerror = null will prevent users from
seeing JavaScript generated errors
onFocus
 Used with frame, select, text, textarea and window
objects.
 Just the opposite of onBlur; i.e. invoked when the
object gets focus.

<body bgcolor=“lightgrey” onBlur=“document.bgColor=‘black’ onFocus=“document.bgColor=‘white’” >


onLoad
 Used with window, frame and image objects
(use with <body ….><frameset ….> and <img
...>)
 Activated when the body, frameset, or image is
loaded

<img name=spinball src=images/spinball.gif onLoad=“startAnimation(this)”>


image loading in browser
onMouseOut and onMouseOver
 Used with area and link objects
 user moves mouse off of an area or link

<map name=flower>
<area name=top coords=“0,0,200,300 href=“javascript:displayMessage()”
onMouseOver=“self.status=‘when you see this message click your left mouse button’ ;
return true”
onMouseOut=“self.status = ‘’ ; return true”>
onReset
 Used with form objects

<form onReset=“alert(‘the form has been reset’)” >


onSelect
 Used with text and textarea objects
 run some Javascript whenever a user selects a piece of
text in a text or textarea object

<input type=text name=line onSelect=“showHelp()” >


onSubmit
 Use with form objects to run a handler whenever a
form has been submitted.
 Usefull to validate all fields prior to actual submission
onUnload
 Just like onLoad but the handler is run when the
window/frame is exited

<body onUnload=“cleanup()” >


HTML Forms Handling
the Form object
 Tag : <form name = n method = get|post action=URL>
 Properties:
 action - action attribute of tag
 elements[ ] - creeated from like named form elements
 encoding - ENCTYPE attribute of tag
 length - length of an elements array
 method - method attribute of tag
 name - name attribute of tag
 target - target attribute of tag, where to display response page
 Methods
 handleEvent( )
 reset( ) - reset all elements to initial value
 submit( ) - submit to server for processing (like submit button)
Text Based Objects
 text
 password
 textarea
 hidden
Properties and methods
 Tag: <input name=name type=fieldtype ….>
 Properties:
 defaultValue - value attribute of tag
 form - form that this field is an element of

 name - name attribute of tag

 type - type attribute of tag (text, password, textarea, hidden)

 value - user entered value or value attribute of tag

 Methods:
 blur( ) * - unselects any selected text

 focus( ) * - readies the field for user input

 handleEvent( ) *

 select( ) * - selects the text in the field

* doesn’t apply to hidden fields


Additional Events
 onKeyDown =
 as soon as the key is depresses
 allows filtering of key strokes before the character is displayed
 onKeyUp =
 as soon as key is released
 onKeyUp = signals the end of a key down and a key up sequence
Carriage returns...
 Forewarned is forearmed….
 Windows \r\n
 Mac \r
 Unix \n
Button objects
 button
 submit
 reset
 checkbox
 radio
button, submit and reset
 Properties:
 name - name attribute of tag
 type - type attribute of tag (button | submit | reset )
 value - value attribute of tag (text on face of button )
 Methods:
 click( ) - simulates the button being clicked on
 handleEvent( ) -
 Additional events-
 onMouseDown =
 onMouseUp =
checkbox object
 Properties:
 checked - true if checked, false otherwise; setting doesn’t cause a click
 defaultChecked - true if CHECKED attribute is present, false otherwise
 name - name attribute of the tag
 type - type attribute of the tag
 value - value attribute of the tag
 Methods:
 click( ) -
 handleEvent( ) -
 Additional events
 onMouseDown =
 onMouseUp =
radio object
 one of n choices
 Properties:
 checked - true if checked, false otherwise; setting doesn’t cause a click
 defaultChecked - true if CHECKED attribute is present, false
otherwise
 name - name attribute of the tag
 type - type attribute of the tag
 value - value attribute of the tag
 Methods:
 click( ) -
 handleEvent( ) -
 Additional events
 onMouseDown =
 onMouseUp =
select object
 Properties:
 length - number of option elements
 option[ ] - element array of the options tags
 name - name attribute of the tag
 selectedIndex - index of selected option
 options[i].defaultSelected -
 options[i].index
 options[I].selected
 Methods:
 blur( ) -
 focus() -
 handleEvent( ) -

You might also like