Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Answer:
The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.
The examples below make use of the alert function for standard text output.
The JavaScript standard library lacks an official standard text output function.
1. JavaScript Lives in a Web Page
2. JavaScript is not server side language. It is client side language because it is interpreted
and run on the browser.
3. It is weakly typed because it does not need to specify datatypes to declare variable (int,
float, double etc) like c/c++.
4. It is not programming language. It Interpreted language because browsers are interpret it.
5. JavaScript is case sensitive.
6. Semicolon(;) is optional
7. String can be enclosed by using single quote () or double quote()
8. // is used to specify single line comment and /* ... */ is used to specify multiline
comment.
Case sensitive
Object oriented
Produces an HTML document
Dynamically typed
Standard operator precedence
Overloaded operators
Reserved words
" and ' can be used in pairs
Scope rules for variables
Strings are very common data types
Rich set of methods available
Arrays have dynamic length
Array elements have dynamic type
Arrays are passed by reference
Array elements are passed by value
Description
Returns a reference to the String function that created the object.
Returns the length of the string.
The prototype property allows you to add properties and methods to an
object.
In the following sections, we will have a few examples to demonstrate the usage of String
properties.
String Methods
Here is a list of the methods available in String object along with their description.
Method
charAt()
Description
Returns the character at the specified index.
concat()
indexOf()
Returns the index within the calling String object of the first
charCodeAt()
lastIndexOf()
localeCompare()
match()
replace()
search()
slice()
split()
substr()
substring()
toLocaleLowerCase(
)
toLowerCase()
toString()
toUpperCase()
valueOf()
toLocaleUpperCase()
Method
anchor()
Description
Creates an HTML anchor that is used as a hypertext target.
big()
blink()
bold()
fixed()
fontcolor()
italics()
link()
small()
fontsize()
strike()
sub()
sup()
In the following sections, we will have a few examples to demonstrate the usage of String
methods.
3. Explain mathematical functions with example.
Answer:
The math object provides you properties and methods for mathematical constants and
functions. Unlike other global objects, Math is not a constructor. All the properties and methods
of Math are static and can be called by using Math as an object without creating it.
Thus, you refer to the constant pi as Math.PI and you call the sine function asMath.sin(x),
where x is the method's argument.
Syntax
The syntax to call the properties and methods of Math are as follows
var pi_val = Math.PI;
var sine_val = Math.sin(30);
Math Properties
Here is a list of all the properties of Math and their description.
Property
E\
LN2
LN10
LOG2E
LOG10E
PI
Description
Euler's constant and the base of natural logarithms, approximately 2.718.
Natural logarithm of 2, approximately 0.693.
Natural logarithm of 10, approximately 2.302.
Base 2 logarithm of E, approximately 1.442.
Base 10 logarithm of E, approximately 0.434.
Ratio of the circumference of a circle to its diameter, approximately
3.14159.
SQRT1_2
SQRT2
In the following sections, we will have a few examples to demonstrate the usage of Math
properties.
Math Methods
Here is a list of the methods associated with Math object and their description
Method
abs()
acos()
asin()
atan()
atan2()
ceil()
cos()
exp()
floor()
log()
max()
min()
pow()
random()
round()
sin()
sqrt()
tan()
toSource()
Description
Returns the absolute value of a number.
Returns the arccosine (in radians) of a number.
Returns the arcsine (in radians) of a number.
Returns the arctangent (in radians) of a number.
Returns the arctangent of the quotient of its arguments.
Returns the smallest integer greater than or equal to a number.
Returns the cosine of a number.
Returns EN, where N is the argument, and E is Euler's constant, the base
of the natural logarithm.
Returns the largest integer less than or equal to a number.
Returns the natural logarithm (base E) of a number.
Returns the largest of zero or more numbers.
Returns the smallest of zero or more numbers.
Returns base to the exponent power, that is, base exponent.
Returns a pseudo-random number between 0 and 1.
Returns the value of a number rounded to the nearest integer.
Returns the sine of a number.
Returns the square root of a number.
Returns the tangent of a number.
Returns the string "Math".
In the following sections, we will have a few examples to demonstrate the usage of the methods
associated with Math.
4. What are popup boxes? Explain the different types of popup boxes with
example.
Answer:
JavaScript supports three important types of dialog boxes. These dialog boxes can be used to
raise and alert, or to get confirmation on any input or to have a kind of input from the users.
Here we will discuss each dialog box one by one.
Alert Dialog Box
An alert dialog box is mostly used to give a warning message to the users. For example, if one
input field requires to enter some text but the user does not provide any input, then as a part of
validation, you can use an alert box to give a warning message.
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one
button "OK" to select and proceed.
Example
<html>
<head>
<script type="text/javascript">
<!-function Warn() {
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="Warn();" />
</form>
</body>
</html>
Example
<html>
<head>
<script type="text/javascript">
<!-function getConfirmation(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
document.write ("User wants to continue!");
return true;
}
else{
document.write ("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getConfirmation();" />
</form>
</body>
</html>
Prompt Dialog Box
The prompt dialog box is very useful when you want to pop-up a text box to get user input.
Thus, it enables you to interact with the user. The user needs to fill in the field and then click
OK.
This dialog box is displayed using a method called prompt() which takes two parameters: (i) a
label which you want to display in the text box and (ii) a default string to display in the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window
method prompt() will return the entered value from the text box. If the user clicks the Cancel
button, the window method prompt()returns null.
Example
The following example shows how to use a prompt dialog box
<html>
<head>
<script type="text/javascript">
<!-function getValue(){
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</form>
</body>
</html>
Alternatively you could use the new Constructor syntax. Apart from the obvious drawback of 5-9
additional assaults on your dainty finger pads (the new part is effectively optional) there is a
more serious issue around ambiguity of intention:
//create a new array with 8 undefined members
var a = new Array(8);
//create a new array containing two predefined elements
var b = new Array(8,9);
a.length; //8
b.length; //2
a[0]; //undefined
b[0]; //8
These two declarations look strikingly similar yet produce entirely different results. Moreover,
lets say someone edits the second statement because they now only want to predefine one
element, the number 8, in array b. Its quite likely they might modify it to the following (and who
could blame them?):
//create a new array containing one predefined element
var b = new Array(8); //Wrong!
Of course this doesnt do what they wanted. The only way to predefine an array with one
primitive number is to use the literal syntax. (Thanks Peter and Dmitry for clarification)
An array can contain any object or primitive type. Multiple data types can co-exist in the same
array.
Accessing an Array element
Array elements are simply object properties and are accessed in the same way as other object
properties. Since property identifiers are always strings, the array index is also a string, not a
number. However when you use subscript notation (square brackets) to access the property, a
number literal can also be used since it will be coerced to a string by the interpreter. Dot notation
accessors will not work for array member access because literal property identifiers cant start
with a number (again, all these behaviours derive from generic object property rules, they are not
array-specific)
var a = ["banana", Math.min, 4, "apple"];
a['1']; //min()
a[2]; //4
Typically it makes sense to use the standard for loop:
var a = ["banana", Math.min, 4, "apple"];
for (var i=0; i < a.length; i++) {
console.log(a[i]);
}
If your array is a long one you may be worried about the additional cost of requesting
array.length on every iteration. To workaround this you can define the array length up front:
var a = makeBigArray();
var aLength = a.length;
for (var i=0; i < aLength; i++) {
console.log(a[i]);
}
Using a forin statement for array iteration is not advised because you may also pick up
enumerable properties from the prototype (see below)
The most important array property is length (strings and functions have length too but the array
definition of length is unique)
ECMA specifies:
The length property of this Array object is always numerically greater than the name of every
property whose name is an array index. In other words its (the numeric value of the last index) +
1.Arrays are not upper-bound. You can add an element at an index greater than (length 1) and
the length property will be modified based on the above definition. Arrays have a maximum
length but its too big for you to worry about.
var a = [3,4,1];
a.length; //3
a[20] = 2;
a.length; //21
//element indexes 3-19 automatically created with value initialized to undefined
a[18]; //undefined
Arrays are lower-bound to zero. If you try to add a value at a negative index you will just be
writing a regular object property (see also associative arrays below)
var a = [];
a[-1] = "giraffe";
a[-1]; //"giraffe"; //because still using a regular object property accessor
a.length; //0
a.toString(); //""
You can manipulate the contents of an existing array by updating its length value. If you reduce
the length property of an existing array, members with indexes greater than or equal to the new
length get discarded (this turns out to be the only way to remove indexes from an array you can
delete an element but this will only delete the value and leave the index in place i.e. your array
becomes sparse = it gets holes in it)
var a = [0,1,2,3,4,5,6];
a.length; //7
a.length = 5;
a.toString(); //"0,1,2,3,4"
a[6]; //undefined
Conversely if you increase the length of an existing array by n your array appears to get n new
members, each with its value initialized to undefined however as Dmitry Soshnikov points out,
this is the standard response to accessing a non existent property. In reality nothing has changed
except the array length.
var a = [0,1,2,3,4,5,6];
a.length; //7
a[9]; //undefined
a[59]; //undefined
a.length = 10;
a.toString(); //"0,1,2,3,4,5,6,,,"
a[9]; //undefined
a[59]; //undefined
There are two additional pseudo-properties of arrays: index and input. These properties are only
present in arrays created by regular expression matches. Array provides a plethora of very useful
utilities, there are too many to go into great detail and you are probably familiar with most preECMA 5 functions. The following array methods are available on the latest versions of all major
browsers
ECMA 5 specifies an additional set of high-order functions all of which have already been
implemented by all the major browsers except IE<=8 (but IE9 preview implements them). Many
of these new methods will already be familiar to those of you who make use of the major
JavaScript frameworks:
indexOf returns the first element equal to the specified value, or -1 if none found
lastIndexOf returns the last element equal to the specified value, or -1 if none found
every returns true if the supplied function returns true when applied to every element
some returns true if the supplied function returns true when applied to at least one
element
forEach applies the supplied function to every element in the array
map creates a new array containing the results of applying the supplied function to every
element in the array
filter creates a new array containing all the elements for which the supplied function
returns true
reduce apply a function simultaneously against two values of the array (from left-to-right)
so as to reduce it to a single value (note: reduce had a different meaning in older versions
of Prototype.js)
reduceRight apply a function simultaneously against two values of the array (from rightto-left) so as to reduce it to a single value
The eternal question. The problem is that in JavaScript when you use typeof against an array it
returns object. I nearly wrote an entire blog post on just this topic. Fortunately kangax already
did just that. The upshot is this latest state-of-the-art version of isArray which is simpler and
more robust than any of its slew of predecessors. It also happens to be the implementation
currently used by both jQuery and Prototype.js
function isArray(o) {
return Object.prototype.toString.call(o) === "[object Array]";
}
Syntax
The basic syntax is shown here.
<script type="text/javascript">
<!-function functionname(parameter-list)
{
statements
}
//-->
</script>
Example
Try the following example. It defines a function called sayHello that takes no parameters
<script type="text/javascript">
<!-function sayHello()
{
alert("Hello there");
}
//-->
</script>
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name of
that function as shown in the following code.
<html>
<head>
<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
/html>
The return Statement
JavaScript function can have an optional return statement. This is required if you want to
return a value from a function. This statement should be the last statement in a function.
or example, you can pass two numbers in a function and then you can expect the function to
return their multiplication in your calling program.
Example
Try the following example. It defines a function that takes two parameters and concatenates
them before returning the resultant in the calling program.
<html>
<head>
<script type="text/javascript">
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}
function secondFunction()
{
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
<body>
<html>
<head>
<script type="text/javascript">
<!-function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>
</body>
</html>
onsubmit Event type
onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.
Example
The following example shows how to use onsubmit. Here we are calling avalidate() function
before submitting a form data to the webserver. Ifvalidate() function returns true, the form will
be submitted, otherwise it will not submit the data.
Try the following example.
<html>
<head>
<script type="text/javascript">
<!-function validation() {
all validation goes here
.........
</div>
</body>
</html>
HTML 5 Standard Events
The standard HTML 5 events are listed here for your reference. Here script indicates a
Javascript function to be executed against that event.
Attribute
offline
onabort
onafterprint
onbeforeonload
onbeforeprint
onblur
oncanplay
Value
script
script
script
script
script
script
script
oncanplaythrough
script
onchange
onclick
oncontextmenu
ondblclick
ondrag
ondragend
ondragenter
script
script
script
script
script
script
script
ondragleave
script
ondragover
ondragstart
ondrop
ondurationchange
onemptied
script
script
script
script
script
onended
onerror
onfocus
onformchange
onforminput
onhaschange
oninput
oninvalid
script
script
script
script
script
script
script
script
Description
riggers when the document goes offline
riggers on an abort event
riggers after the document is printed
riggers before the document loads
riggers before the document is printed
riggers when the window loses focus
riggers when media can start play, but might has to stop for
buffering
riggers when media can be played to the end, without
stopping for buffering
riggers when an element changes
riggers on a mouse click
riggers when a context menu is triggered
riggers on a mouse double-click
riggers when an element is dragged
riggers at the end of a drag operation
riggers when an element has been dragged to a valid drop
target
riggers when an element is being dragged over a valid drop
target
riggers at the start of a drag operation
riggers at the start of a drag operation
riggers when dragged element is being dropped
riggers when the length of the media is changed
riggers when a media resource element suddenly becomes
empty.
riggers when media has reach the end
riggers when an error occur
riggers when the window gets focus
riggers when a form changes
riggers when a form gets user input
riggers when the document has change
riggers when an element gets user input
riggers when an element is invalid
onkeydown
onkeypress
onkeyup
onload
onloadeddata
onloadedmetadata
script
script
script
script
script
script
onloadstart
onmessage
onmousedown
onmousemove
onmouseout
onmouseover
onmouseup
onmousewheel
onoffline
ononline
onpagehide
onpageshow
onpause
onplay
onplaying
onpopstate
onprogress
onratechange
onreadystatechange
onredo
onresize
onscroll
onseeked
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
onseeking
script
onselect
onstalled
onstorage
onsubmit
onsuspend
script
script
script
script
script
ontimeupdate
onundo
onunload
onvolumechange
script
script
script
script
onwaiting
script
Expires The date the cookie will expire. If this is blank, the cookie will expire when the visitor
quits the browser.
Path The path to the directory or web page that set the cookie. This may be blank if you want to
retrieve the cookie from any directory or page.
Secure If this field contains the word "secure", then the cookie may only be retrieved with a secure
server. If this field is blank, no such restriction exists.
Name=Value Cookies are set and retrieved in the form of key-value pairs
Cookies were originally designed for CGI programming. The data contained in a cookie is
automatically transmitted between the web browser and the web server, so CGI scripts on the
server can read and write cookie values that are stored on the client.
JavaScript can also manipulate cookies using the cookie property of theDocument object.
JavaScript can read, create, modify, and delete the cookies that apply to the current web page.
Storing Cookies
The simplest way to create a cookie is to assign a string value to the document.cookie object,
which looks like this.
document.cookie = "key1=value1;key2=value2;expires=date";
Here the expires attribute is optional. If you provide this attribute with a valid date or time, then
the cookie will expire on a given date or time and thereafter, the cookies' value will not be
accessible.
Note Cookie values may not include semicolons, commas, or whitespace. For this reason, you
may want to use the JavaScript escape() function to encode the value before storing it in the
cookie. If you do this, you will also have to use the corresponding unescape() function when
you read the cookie value.
Example
Try the following. It sets a customer name in an input cookie.
<html>
<head>
<script type = "text/javascript">
<!-function WriteCookie()
{
if( document.myform.customer.value == "" ){
alert("Enter some value!");
return;
}
cookievalue= escape(document.myform.customer.value) + ";";
document.cookie="name=" + cookievalue;
Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month.
<html>
<head>
<script type="text/javascript">
<!-function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
Deleting a Cookie
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie
return nothing. To do this, you just need to set the expiry date to a time in the past.
Example
Try the following example. It illustrates how to delete a cookie by setting its expiry date to one
month behind the current date.
<html>
<head>
<script type="text/javascript">
<!-function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
10.Describe briefly three major differences between java and java script.
Answer
Difference between Java vs JavaScript
Here is my list of key differences between JavaScript and Java as programming languages. I
have worked both on them, mainly used Java for all Server Side development, Android and
JavaScript for writing client side scripts to do validation, interactivity, animation and ajax calls.
1. Execution Environment
First difference between Java and JavaScript is that Java is compiled + interpreted language, Java
code is fist compiled into class files containing byte code and than executed by JVM, on the
other hand JavaScript code is directly executed by browser. One more difference which comes
form this fact is that, Java is run inside JVM and needs JDK or JRE for running, on there other
hand JavaScript runs inside browser and almost every modern browser supports JavaScript.
to write code using jQuery rather than using plain old JavaScript code, even if its as simple as
calling getElementById() or getElementByName() methods to retrieve DOM elements.
6. Block vs Function based Scoping
Java mainly uses block based scoping i.e. a variable goes out of scope as soon as control comes
out of the block, unless until its not a instance or class variable. On the other hand JavaScript
mainly uses function based scoping, a variable is accessible in the function they are declared. If
you have a global variable and local variable with same name, local will take precedence in
JavaScript.
7. Constructors
Java has concept of constructors, which has some special properties e.g. constructor
chaining and ensuring that super class constructor runs before sub class, on the other hand
JavaScript constructors are just another function. There is no special rules for constructors in
JavaScript e.g. they cannot have return type or their name must be same as class.
8. NullPointerException
JavaScript is much more forgiving than Java, you don't have NullPointerException in
JavaScript, your variable can accept different kinds of data because of JavaScript is dynamically
typed language.
9. Applicability
Last but not the least, JavaScript has it's own space, sitting cozy along with HTML and CSS in
Web development, while Java is everywhere. Though both has good number of open source
libraries to kick start development, but jQuery has certainly brings JavaScript on fore front.
match() method
compares a RE and a string to see whether they match.
replace() method
finds out if a RE matches a string and then replaces a matched string with a new string
search() method
Format: string.search(reg-exp)
Searches the string for the first match to the given regular expression
returns an integer that indicates the position in the string (zero-indexed).
If no match is found, the method will return 1.
Similar to the indexOf() method,
Example: To find the location of the first absolute link within a HTML document
pos = htmlString.search(/^<a href = http:\/\/$/i);if ( pos != -1) { alert( First absolute
link found at + pos +position.);}else { alert ( Absolute links not found)
match() method
Format: string.match( regular_expression )
returns an array of all the matching strings found in the string given. If no matches are found,
then match() returns false.
Example: To check the proper format for a phone number entered by a user, with the form of
(XXX) XXX-XXXX.
function checkPhone( phone ) { phoneRegex = /^\(\d\d\d\) \d\d\d-\d\d\d\d$/; if( !
phone.match( phoneRegex ) ) { alert( Please enter a valid phone number ); return
false; } return true;}
replace() method
Format string.replace(reg_exp)
Properties: replaces matches to a given regular expression with some new string.
Example: To replace every newline character (\n) with a break <br /> tag,
comment = document.forms[0].comments.value;
/* assumes that the HTML form is the first one present in the document, and it has a field
named comments */
comment = comment.replace( /\n/g, <br />);
function formatField( fieldValue ) { return fieldValue = fieldValue. replace(/\n/g, <br />);}
The function accepts any string as a parameter, and returns the new string with all of the newline
characters replaced by <br /> tags.
The Document Object Model (DOM) is a programming API for HTML and XML documents. It
defines the logical structure of documents and the way a document is accessed and manipulated.
In the DOM specification, the term "document" is used in the broad sense - increasingly, XML is
being used as a way of representing many different kinds of information that may be stored in
diverse systems, and much of this would traditionally be seen as data rather than as documents.
Nevertheless, XML presents this data as documents, and the DOM may be used to manage this
data.
The Document Object Model is a programming API for documents. The object model itself
closely resembles the structure of the documents it models. For instance, consider this table,
taken from an HTML document:
<TABLE>
<ROWS>
<TR>
<TD>Shady Grove</TD>
<TD>Aeolian</TD>
</TR>
<TR>
<TD>Over the River, Charlie</TD>
<TD>Dorian</TD>
</TR>
</ROWS>
</TABLE>
The Document Object Model represents this table like this:
In the Document Object Model, documents have a logical structure which is very much like a
tree; to be more precise, it is like a "forest" or "grove" which can contain more than one tree.
However, the Document Object Model does not specify that documents be implemented as a tree
or a grove , nor does it specify how the relationships among objects be implemented in any way.
In other words, the object model specifies the logical model for the programming interface, and
this logical model may be implemented in any way that a particular implementation finds
convenient. In this specification, we use the term structure model to describe the tree-like
representation of a document; we specifically avoid terms like "tree" or "grove" in order to avoid
implying a particular implementation. One important property of DOM structure models
is structural isomorphism: if any two Document Object Model implementations are used to
create a representation of the same document, they will create the same structure model, with
precisely the same objects and relationships.
1. If no password has been typed in the first box, focus on that box and return false
2. If the two passwords are not the same, focus and select the first box and return false if
they are the same, return true
</head>
<body bgcolor="#FFFFFF">
<form name="emp" action="" onsubmit="return validate_form();" method="post">
<table align="center" width=40% width="100%" cellspacing="2" cellpadding="2" border="5">
<tr>
<td colspan="2" align="center"><b>Employee Registration Form.</b></td>
</tr>
<tr>
<td align="left" valign="top" width="41%">Employee Name<span
style="color:red">*</span></td>
<td width="57%"><input type="text" value="" name="emp_name" size="24"></td>
</tr>
<tr>
<td align="left" valign="top" width="41%">Employee Number<span
style="color:red">*</span></td>
<td width="57%">
<input type="text" value="" name="num" onkeypress="return isNumberKey(event)"
size="24"></td>
</tr>
<tr>
<td align="left" valign="top" width="41%">Address</td>
<td width="57%"><textarea rows="4" maxlen="200" name="S2" cols="20"></textarea></td>
</tr
<tr >
<td align="left" valign="top" width="41%">Contact Number</td>
<td width="57%">
<input type="text" value="" onkeypress="return isNumberKey(event)" name="txtFName1"
size="24"></td>
</tr>
<tr >
<td align="left" valign="top" width="41%">Job Location</td>
<td width="57%"><select name="mydropdown">
<option value="Default">Default</option>
<option value="Chennai">Chennai</option>
<option value="Bangalore">Bangalore</option>
<option value="Chennai">Pune</option>
<option value="Bangalore">Mysore</option>
<option value="Chennai">Chandigarh</option>
</select></td>
</tr>
<tr >
<td align="left" valign="top" width="41%">Designation</td>
<td width="57%">
<select name="mydropdown">
<option value="Default">Default</option>
<option value="Systems Engineer">Systems Engineer</option>
Exception Handling
Exceptions are time to learn how to stop
Event Handling
Events occur when some sort of
Constructor in java
Java constructors are special functions
that can only be called at object creation.
2
Java constructor is invoked at the time of In JavaScript, the constructor property
object creation. It constructs the values i.e. returns the constructor function for an
provides data for the object that is why it object.
is known as constructor.
The with keyword is used as a kind of shorthand for referencing an object's properties or
methods.
The object specified as an argument to with becomes the default object for the duration of the
block that follows. The properties and methods for the object can be used without naming the
object.
Syntax
The syntax for with object is as follows
with (object){
properties used without the object name and dot
}
Example
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
function addPrice(amount){
with(this){
price = amount;
}
}
function book(title, author){
this.title = title;
this.author = author;
this.price = 0;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
b.Name attributes
There would be no particular need to apply a name attribute to a form. The form name attribute is
not valid in XHTML. Using an ID rather than a name to identify and obtain a reference to a form
is generally preferable.
On the other hand, name attributes on form elements are valid and necessary for successful
submission to server side code. If you are associating a label element with a form element using
a for attribute, the form element needs an ID:
<label for="firstName">First Name: </label>
<input type="text" name="firstName" id="firstName" />
Thus, form elements will typically include a name attribute and may also include an ID attribute
if needed. Keep in mind that IDs need to be unique in the document, while the same name may
be applied to multiple form elements. This is typical with sets of radio inputs and often
checkboxes as well.
1
2
3
Figure: graphical representation of an event dispatched in a DOM tree using the DOM event
flow
The target's ancestors are determined before the initial dispatch of the event. If the target node is
removed during the dispatching, or a target's ancestor is added or removed, the event propagation
will always be based on the target node and the target's ancestors determined before the dispatch.
Some events may not necessarily accomplish the three phases of the DOM event flow, e.g. the
event could only be defined for one or two phases. As an example, events defined in this
specification will always accomplish the capture and target phases but some will not accomplish
the bubbling phase ("bubbling events" versus "non-bubbling events", see also the Event.bubbles
attribute).
22 Create a simple HTML page which includes simple form write a script to
extract the data from the form when the submit button is clicked. Display
the extracted data in a new document
Answer
<html>
<head>
<title>contact</title>
<script type="text/javascript">
function addtext()
{
var fname = document.myform.first_name.value;
var lname = document.myform.last_name.value;
var email = document.myform.email.value;
document.writeln("thank you! You have just entered the following:");
document.writeln("<pre>");
a.length = 10;
console.log(a[13]); // undefined, when reducing the length elements after length+1 are removed
console.log(a.length); // 10
The result of a match between a regular expression and a string can create an array. This array
has properties and elements that provide information about the match. An array is the return
value of RegExp.exec, String.match, and String.replace. To help explain these properties and
elements, look at the following example and then refer to the table below:
// Match one d followed by one or more b's followed by one d
// Remember matched b's and the following d
// Ignore case
var myRe = /d(b+)(d)/i;
var myArray = myRe.exec("cdbBdbsbz");
}
</script>
</head>
<body>
<p>Welcome to JavaScript!</p>
</body>
</html>
1
2
3
4
How it Works?
Line 8 declares a variable called username, via the keyword var. A variable is a named storage
location that holds a value. Once the variable is declared, you can assign (and re-assign) a value
to that variable, via the assignment operator '=' (Line 9).
Line 9 invokes the prompt(promptingString, defaultString?) function to pop out a dialog box,
and reads in the string entered by the user. The string read is assigned to the variable username.
The function prompt() is similar to the alert(), but it accepts a user's input.
In Line 10, the confirm(aString) function puts up the message and returns either true or false,
depending on whether the user hits the OK or Cancel button.
If the result is true, Line 11 prints "Hello, username!". Otherwise, Line 13 prints "Hello, world!".
TRY: Instead of printing the greeting message using document.write(), do it via an alert().
language, youre probably overwhelmed with the number of resources available for learning it.
You may have read some other books or even tried your hand at some basic scripting. Its
possible to rapidly accelerate your mastery of both JavaScript and browser scripting in general
by familiarizing yourself with the fundamentals. If you already know another programming
language and can become proficient with the four or so basic concepts in the language, you can
say goodbye to months of gradual discovery and terrible code and jump right into the really fun
stuff. John Resig of jQuery and Mozilla fame was one of the first to describe a common
development path for new coders when learning
Object references are everywhere: Most useful operations involve passing references to very
large objects like the DOM (Document Object Model) or an element on the page or a function.
The DOM itself is a very large hierarchical collection of object and element references that can
be manipulated as easily as setting a property. You can make your own objects and
namespaces: Indeed, one of the first things developers realize is that JavaScript is OO (Object
Oriented) programming. While they may not fully understand all the OO features available to
them, they begin by making some basic APIs that follow very elementary OO principals.
Object prototypes let you create OO classes: Once coders understand that they can create
instances of objects and functions to build pseudo-classes, someone points out the prototype
constructor to them and somewhere in the learners brains a light goes off. They begin building
elaborate class-based APIs for every imaginable purpose but begin hitting roadblocks related to
scope and maintaining object references between pieces of their programs. Closures are God:
As Resig pointed out in his now-famous talk, at this stage coders generally discover how
closures can help solve some of the problems encountered in stage 3 when building complex
interconnected APIs. They may not, however, fully understand the minefield that closures are.
Memory leaks, difficult-to-follow scope chains, and spaghetti code are coexistent with a coders
first attempts at closures.