JavaScript Basics for Web Development
JavaScript Basics for Web Development
Features of JavaScript
JavaScript is an open source scripting language.
It is lightweight.
It creates network-centric applications.
It is platform independent.
It validates form data.
It reduces server load.
Advantages of JavaScript
JavaScript saves server traffic.
It performs the operations very fast.
It is simple to learn and implement.
It is versatile.
JavaScript pages are executed on the client side.
JavaScript extends its functionality to the web pages.
Disadvantages of JavaScript
JavaScript cannot be used for networking applications.
It doesn't have any multithreading or multiprocessor capabilities.
It has security issues being a client-side scripting language.
What is a script?
Script is a small, embedded program.
The most popular scripting languages on the web are, JavaScript or VBScript.
HTML does not have scripting capability, you need to use <script> tag.
The <script> tag is used to generate a script.
The </script> tag indicates the end of the script or program.
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 2
The 'type' attribute indicates which script language you are using with the type attribute.
You can also specify the <script language> using the 'language' attribute.
<SCRIPT LANGUAGE=”JAVASCRIPT”>
-------Javascript statements-----
</SCRIPT>
The script tag can be placed either in the head or the body of the HTML document. But it
is preferred to place the script tag in the head of the document to ensure that all
JavaScript definitions have been made before the body of the document is displayed.
Consider the following sample code which displays “ This is my first java script
program” in the browser.
</HTML>
<BODY>
<SCRIPT
LANGUAGE="JAVASCRIPT">
[Link]("This is my first
java script program")
</SCRIPT>
</BODY>
</HTML>
Hiding Scripts using Comment tags:
All browsers do not support JavaScript. Older browsers, such as Netscape Navigator 1,
Internet Explorer 2 do not recognize the </SCRIPT> tag and as a consequence, display as
text all the JavaScript statements between <SCRIPT> and </SCRIPT> .
In order to prevent this, you can have the JavaScript statements surrounded by
HTML comment tags ( <!-- and - -> ). These comment tags cause the JavaScript
statements to be treated as comments by browsers, which do not support JavaScript.
Browsers that do not support JavaScript to use this tag will display HTML
enclosed within a <NOSCRIPT> tag in plain text. Browsers that support JavaScript
ignore the code within this tag.
<HTML>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!- -
[Link]("This is my first java script program")
-->
</SCRIPT>
<NOSCRIPT>
<B> upgrade to java enabled browser </B>
</NOSCRIPT>
</BODY>
</HTML>
JavaScript Entities:
JavaScript entities allow the value of an HTML attribute to be provided by a JavaScript
expression. This allows the attribute values to be dynamically calculated during the
loading of a page. JavaScript entities have to be used in the following manner
&{ Expression };
where expression is the JavaScript expression to be evaluated.
Note:
Microsoft Internet Explorer does not support JavaScript Entities.
Eg:
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 5
<html>
<head> <script language=”javascript”>
col=”red”
</script>
</head>
<body>
<h1 color=”&col”>this text will be displayed in red color</h1>
</body>
</html>
The script tag provides an alternative way for including the JavaScript code in an HTML
document using the “SRC” attribute, which may be used to specify a file containing the
JavaScript statements.
Example:
<html>
<head>
</head>
<body>
<script language=”javascript” src=”[Link]”>
</script></body>
</html>
In the above example “[Link]” is the file containing JavaScript statements as shown
below
---------------------------------------[Link]------------------------------
[Link](“THIS TEXT IS DISPLAYED FROM THE FILE [Link]”)
==============================================================
OrderNumber
Name
$Rs
Rs_$
Data Types:
JavaScript supports four primitive types of values and supports complex types, such
as arrays and objects.
The four primitive types are:
1. Number
Consists of integers and floating point numbers and a special NaN (not a
number) value.
2. Boolean
Consists of the logical values true and false
3. String
Consists of string values that are enclosed in single or double quotes.
[Link]
Consists of a single value , undefined , which is used to indicate that a variable
has not been assigned a value.
Operators:
The set of operators that JavaScript uses is very similar to c,c++ programming
languages. The operators can be classified as bellow:
Assignment
Comparision
Arithmetic
BitWise
Logical
String
Special
Arithmetic operators:
+ Addition 5+10 15
- Subtraction 5 – 10 -5
* Multiplication 5 * 10 15
/ Division 22 / 7 3.14159
% Modulus 5 mod 2 1
++ Increment operator
-- Decrement operator
of the operand for use in the expression. If the operator follows its operand, the value of
the operand is obtained before incrementing or decrementing it.
For example
x=10;
y= ++x;
sets y to 11. However if you write the code as
x=10;
y=x++;
y is set to 10. Either way, x is set to 11.
Relational Operators
Logical operators are used to combine one or more relational expressions. They compare
two relational expressions and return true or false value based on the result of the
comparison.
The following table lists the commonly used Logical operators to construct a logical
expression.
For Example: ( X < 10) and (Y > 10)
Bitwise Operators
Bitwise operators can be applied only to char and int data types. You cannot use bitwise
operators on float, double, long double, void, Boolean, or other, more complex types.
Operator Action
& AND
| OR
^ XOR
~ NOT (one’s complement)
>> Shift right
<< Shift left
>>> Unsigned right shift
Bitwise Operators
Operation on bits
Following are the operations used commonly in JavaScript on bits
1) AND (&&)
Input 1 Input 2 Result
Example:
0 0 0
1.) k=3 && 0 result : k=0
0 1 0
1 0 0
2.) i=1,j=1;
1 1 1
k=I && j result k=1
And truth table
3.) i=5, j=-14;
k=I && j; result k=1; Input 1 Input 2 Result
0 0 0
2) OR ( || ) 0 1 1
1 0 1
Example: 1 1 1
1.) k=3 || 0 result : k=1 OR truth table
2.) i=1,j=1;
k=I || j result k=0
1. If Statement
IF statement is a conditional branching statement.
In 'IF' statement, if the condition is true a group of statement is executed. And if
the condition is false, the following statement is skipped.
Syntax : If statement
if(condition)
{
//Statement 1;
//Statement 2;
}
<html>
<body>
<script type="text/javascript">
var num = prompt("Enter Number");
if (num > 0)
{
alert("Given number is Positive!!!");
}
</script>
</body>
</html>
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 11
Output:
2. If – Else Statement
If – Else is a two-way decision statement.
It is used to make decisions and execute statements conditionally.
if (condition)
{
//Statement 1;
}
else if(condition)
{
//Statement 2;
}
else
{
//Statement 3;
}
<html>
<head>
<script type="text/javascript">
var no = prompt("Enter a Number to find Odd or Even");
no = parseInt(no);
if (isNaN(no))
{
alert("Please Enter a Number");
}
else if (no == 0)
{
alert("The Number is Zero");
}
else if (no % 2)
{
alert("The Number is Odd");
}
else
{
alert("The Number is Even");
}
</script>
</head>
</html>
Output:
3. Switch Statement
Switch is used to perform different actions on different conditions.
It is used to compare the same expression to several different values.
Syntax
switch(expression)
{
case condition 1:
//Statements;
break;
case condition 2:
//Statements;
break;
case condition 3:
//Statements;
break;
.
.
case condition n:
//Statements;
break;
default:
//Statement;
}
<html>
<head>
<script type="text/javascript">
var day = prompt("Enter a number between 1 and 7");
switch (day)
{
case (day="1"):
[Link]("Sunday");
break;
case (day="2"):
[Link]("Monday");
break;
case (day="3"):
[Link]("Tuesday");
break;
case (day="4"):
[Link]("Wednesday");
break;
case (day="5"):
[Link]("Thursday");
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 16
break;
case (day="6"):
[Link]("Friday");
break;
case (day="7"):
[Link]("Saturday");
break;
default:
[Link]("Invalid Weekday");
break;
}
</script>
</head>
</html>
Output:
4. For Loop
For loop is a compact form of looping.
Syntax
<html>
<body>
<script type="text/javascript">
function palindrome()
{
var revstr = " ";
var strr = [Link]("strr").value;
var i = [Link];
for(var j=i; j>=0; j--)
{
revstr = revstr+[Link](j);
}
if(strr == revstr)
{
alert(strr+" - is Palindrome");
}
else
{
alert(strr+" - is not a Palindrome");
}
}
</script>
<form>
Enter a String or Number: <input type="text" id="strr"
name="checkpalindrome"><br>
<input type="submit" value="Check" onclick="palindrome();">
</form>
</body>
</html>
Output:
5. For-in Loop
For-in loop is used to traverse all the properties of an object.
It is designed for looping through arrays.
Syntax
6. While Loop
While loop is an entry-controlled loop statement.
It is the most basic loop in JavaScript.
It executes a statement repeatedly as long as expression is true.
Once the expression becomes false, the loop terminates.
Syntax
while (condition)
{
//Statements;
}
<html>
<body>
<script type="text/javascript">
var no1=0,no2=1,no3=0;
[Link]("Fibonacci Series:"+"<br>");
while (no2<=10)
{
no3 = no1+no2;
no1 = no2;
no2 = no3;
[Link](no3+"<br>");
}
</script>
</body>
</html>
Output:
7. Do-While Loop
Do-While loop is an exit-controlled loop statement.
Similar to the While loop, the only difference is condition will be checked at the
end of the loop.
The loop is executed at least once, even if the condition is false.
Syntax
do
{
//Statements;
}
while(condition);
<html>
<body>
<script type ="text/javascript">
var i = 0;
do
{
[Link](i+"<br>")
i++;
}
while (i <= 5)
</script>
</body>
</html>
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 22
Output:
0
1
2
3
4
5
8. Break Statement
Break statement is used to jump out of a loop.
It is used to exit a loop early, breaking out of the enclosing curly braces.
Syntax:
break;
9. Continue Statement
Continue statement causes the loop to continue with the next iteration.
It skips the remaining code block.
Syntax:
continue;
=======================================================
Aaraylength is the length of an array, which denotes the number of elements that can
be stored in the array. The first element of an array has an index 0, the next element
has an index 1 and so on.
Eg:
To store names of five students the array can be declared as follows:
Student = new Array(5)
[Link](Stuent[2])
Javascript does not impose any restrictions on the type of elements stored in an
array. you can store an integer, string, Boolean value and also an array object as
elements of an array.
For example consider the following
myArray = new Array( 1, “India”, 3.55, 4)
the length of myArray is 10 and it has the following statements,
myArray[0]=1
myArray[1]=”India”
myArray[2]=3.55
myArray[3]=4
E.g:
[Link]([Link]())
This Stmt will display the output as:
1,2,3,4,5,6
Join(separator) Joins array element together but separated by the separator string.
The function returns the output as a string
E.g
[Link]([Link](“-“))
This Stmt will display the output as:
1-2-3-4-5-6
Sort() Sorts the contents of an array based upon the ascii value of each
character.
e.g
arr=new Array(1,2,3,10)
[Link]([Link]())
This Stmt will display the output as:
1,10,2,3
reverse() Reverse the contents of the array. The last element becomes first and
the first element becomes the last.
E.g
[Link]([Link]())
This Stmt will display the output as:
6,5,4,3,2,1
pop() It removes the last element from an array and returns that element.
It adds one or more elements to the end of an array and returns the
push()
new length of the array.
2. String Object:
String value
Alphanumeric data in JavaScript is known as “String”, which is one or more
characters enclosed within single or double quotes. If a string begins with single
quote then it has to end with a single quote. Similarly, if a string begins with double
quote it must end with a double quote.
The string object provides the following methods, which can be used to manipulate
any string
Eg:
Str = “ I Love India”
[Link]()
[Link](Str) would displays the out put as
i love india
Eg:
Str = “I Love India”
Temp= Str. substring (7)
[Link](Temp) would displays the out put as
India
Eg:
Str = “I Love India”
Temp= Str. subString (0,6)
[Link](Temp) would displays the out put as
I Love
Eg:
Str = “I Love India”
Temp= Str. charAt (8)
[Link](Temp) would displays the out put as
n
The Boolean object allows the creation of user defined Boolean values.
For example , you can declare the object mytrue to represent the Boolean true and
object myfalse to represent the Boolean false. It can be done in the following manner.
now you will be able to use the objects myTrue and MyFalse as Boolean true and
Boolean false respectively.
Method 2:
Var = new Date (year, month , day, hours, minutes, seconds, milliseconds)
Creates an instance of the date object with the date specified by the year, month, day,
hours, seconds, and milliseconds. The year and month parameters must be specified,
the other parameters are optional.
Note:
If the optional parameters are included, then they must specified in the given order.
getDate() Returns the day of the month from the date object
getDay() Returns the day of the week from the date object, starting Monday as 1.
getMonth() Returns the month of the year from the date object. It returns ‘0’ for
January, ‘1’ for February so on and ‘11’ for December.
setMonth() Sets the month of the year for the date object.
getYear() Returns the year from the date object.
setYear() Sets the year for the date object.
getFullYear() Returns the year in four digit format from the date object.
setFullYear() Sets the year in four digit format for the date object.
getTime() Returns the time in milliseconds since midnight January 1 , 1970 from
the date object.
getHours() Return the hours, minutes and seconds from the date object.
getMinutes()
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 31
getSeconds()
setHours() Sets the hours, minutes and seconds for the date object.
setMinutes()
setSeconds()
Consider the following program which displays the system date and time.
<HTML>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
d=new Date()
[Link](" d= "+d)
[Link](" <br> [Link]()
"+[Link]())
[Link](" <br> [Link]()
"+[Link]())
[Link](" <br> [Link]()
"+[Link]())
[Link](" <br> [Link]()
"+[Link]())
</SCRIPT>
</BODY>
</HTML>
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>
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.
It sets and returns the value of the method attribute in a form that is GET or
Method
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.
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”>
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 34
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”>
Property Description
defaultValue It sets or returns the default value of a password field.
It sets or returns the maximum number of characters allowed in a password
maxLength
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.
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”>
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.
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>
Collection Description
options It returns a collection of all the options in a dropdown list.
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.
Method Description
add() It adds an option to a dropdown list.
remove() It removes an option from a dropdown list.
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 36
6. Option Object
Option object represents an HTML <option> element.
It is used to add items to a select element.
Syntax:
<option value> . . . </option>
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.
Methods Description
blur() It removes the focus from the option.
focus() It gives the focus to the option.
<html>
<head>
<script type="text/javascript">
function optionfruit(select)
{
var a = [Link];
var fav = [Link][a].value;
if(a==0)
{
alert("Please select a fruit");
}
else
{
[Link]("Your Favorite Fruit is <b>"+fav+".</b>");
}
}
</script>
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 37
</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([Link]);">
</form>
</body>
</html>
Output:
7. Radio Object
Radio object represents a radio button in an HTML form.
Syntax:
<input type= “radio”>
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.
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”>
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>
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.
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 39
The document object represents your web [Link] you want to access any element in an
HTML page, you always start with accessing the document object.
Method Description
write("string") writes the given string on the doucment.
writes the given string on the doucment with newline
writeln("string")
character at the end.
getElementById() returns the element having the given id value.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name.
Method Description
[Link](element) Create an HTML element
[Link](element) Remove an HTML element
[Link](element) Add an HTML element
[Link](new, old) Replace an HTML element
[Link](text) Write into the HTML output stream
win1=open("[Link]","cal1","menubar=no, toolbar=yes");
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.
It returns the boolean value indicating whether a window has been closed or
Closed
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.
Screen It returns the X coordinate of the window relative to the screen.
Screen 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.
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().
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 42
[Link] Object
Navigator object is the representation of Internet browser.
It contains all the information about the visitor's (client) browser.
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.
Description
Method
javaEnabled() It specifies whether or not the browser is Java enabled.
<html>
<body>
<script type="text/javascript">
[Link]("<b>Browser: </b>"+[Link]+"<br><br>");
[Link]("<b>Browser Version: </b>"+[Link]+"<br><br>");
[Link]("<b>Browser Code:
</b>"+[Link]+"<br><br>");
[Link]("<b>Platform: </b>"+[Link]+"<br><br>");
[Link]("<b>Cookie Enabled:
</b>"+[Link]+"<br><br>");
[Link]("<b>User Agent: </b>"+[Link]+"<br><br>");
[Link]("<b>Java Enabled: </b>"+[Link]()+"<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
[Link] Object
History object is a part of the window object.
It is accessed through the [Link] property.
It contains the information of the URLs visited by the user within a browser
window.
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.
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.
[Link] Object
Location object is a part of the window object.
It is accessed through the '[Link]' property.
It contains the information about the current URL.
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.
Method Description
assign() It loads a new document.
reload() It reloads the current document.
replace() It replaces the current document with a new one.
Conversion functions:
eval() This function converts a string to a numerical value. For example consider
the following
Sum=eval(“1234”)
When the above statement is executed, it will assign the value 1234 to the
variable [Link] function eval() takes a string as a parameter and returns a
numerical value. If the string value, which is passed as a parameter doesnot
represent a valid numerical value , then it results in an error.
parseInt() This function extracts the first integer part from a given string. If the string
does not begin with an integer then this function returns ‘0’.
For example num=parseInt(“123string”) will result in a value 123 being
assigned to the variable num and num=parseInt(“xyz123”) will result in a
value ‘NaN’ being assigned to the variable num because the string xyz123
does not begin with an integer.
ParseFloat() This function extracts the first floating-point number from a given string.
For example parseFloat(“1.23xyz”) returns 1.23.
<html>
<body>
<script type="text/javascript">
[Link]("<b>Path Name: </b>"+[Link]+"<br><br>");
[Link]("<b>Href: </b>"+[Link]+"<br><br>");
[Link]("<b>Protocol: </b>"+[Link]+"<br><br>");
</script>
</body>
</html>
Output:
Example :
To remove all characters other than alphabets and numbers
var str=[Link];
var re=/[^A-Za-z0–9]/g
var lowRegStr = [Link]().replace(re, '');
Functions in JavaScript:
Functions Description
Returns true, if the object is Not a Number.
isNan()
Returns false, if the object is a number.
If the string begins with a number, the function reads through the string
parseFloat until it finds the end of the number; cuts off the remainder of the string
(string) and returns the result.
If the string does not begin with a number, the function returns NaN.
If the string begins with an integer, the function reads through the string
until it finds the end of the integer, cuts off the remainder of the string and
parseInt
returns the result.
(string)
If the string does not begin with an integer, the function returns NaN (Not
a Number).
String
Converts the object into a string.
(object)
eval() Returns the result of evaluating an arithmetic expression.
User-defined Functions
User-defined function means you can create a function for your own use. You can
create yourself according to your need.
In JavaScript, these functions are written in between the <HEAD> tag of the
HTML page.
Functions are set of statements, which perform a specific task. Functions may or may not
return a value. Every function has a name and an argument list, which is optional. In
JavaScript functions are declared in the following manner.
The keyword function indicates that the following statements will be part of the function.
The scope of the function is defined by {} and statements form the body of the function.
Functions are not executed until they are explicitly called using function call statements.
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 example code.
Example:
In the bellow program a function is designed to perform the task of calculating the time
required to travel a certain distance at a certain speed.
<HTML>
<head>
<SCRIPT LANGUAGE="JAVASCRIPT">
function caltimedistance()
{
var x = parseFloat([Link])
var y = parseFloat([Link])
result=x/y
[Link]=result
}
</SCRIPT>
</head>
<BODY>
<form name=f1>
<h1> Time to distance calculator </h1>
<br> Distance in miles <input type=text name=t1>
<br> Speed in miles per hour <input type=text name=t2>
<br> <input type=button value=claculate onclick=caltimedistance()>
<br> answer (nuber of hours)<input type=text name=t3>
</form>
</BODY>
</HTML>
Function Parameters
A function can take multiple parameters separated by comma.
function inc(sum){
sum=sum+200;
return sum;
}
Example: here inc function increments the value by 200 and returns value to the other
function add
function add(){
n1= parseInt([Link]);
n2= parseInt([Link]);
sum= n1+n2;
newsum=inc(sum)
[Link](" result "+ newsum);
}
function inc(sum){
sum=sum+200;
return sum;
sum=sum+10;
}
[Link] Method
The Alert method displays a dialog box containing a message and an OK button.
Syntax
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 58
Alert(“Good Morning”)
2 Confirm Method
The Confirm() method is similar to the alert() method except that it produces a dialog
box with a message, an OK button, and a Cancel button. The confirm method returns
true if the user clicks OK and false if the user Clicks Cancel.
Syntax
Val= confirm("Good Morning")
The Prompt method displays a message to the user and prompts the user to type
information into a text field. It provides the capability to display default text in the text
filed.
Syntax
Prompt(“text”,” default text_Field_value”)
Eg:
a=prompt("Good Morning","india")
Event Handlers
Event
Description
Handler
onAbort It executes when the user aborts loading an image.
It executes when the input focus leaves the field of a text, textarea or a
onBlur
select option.
It executes when the input focus exits the field after the user modifies its
onChange
text.
In this, a function is called when an object in a button is clicked, a link is
onClick pushed, a 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
onFocus
but not selecting input from the field.
onLoad It executes when a window or image finishes loading.
The JavaScript code is called when the mouse is placed over a specific
onMouseOver
link or an object.
The JavaScript code is called when the mouse leaves a specific link or an
onMouseOut
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.
<html>
<head>
<SCRIPT LANGUAGE="javascript">
function sumitinfo(){
if ( [Link]=="")
alert("enter login name")
else if ( [Link]=="")
alert("enter passowd name")
}
</SCRIPT>
</head>
<body bgcolor="red"><pre>
<form name=qz>
wellcome to:
<h1> Nisiki Technologies(p) L.t.d</h1>
<hr>
login name <INPUT TYPE="TEXT" name="log" VALUE="">
Password <INPUT TYPE="Password" TEXT" NAME="pas"
VALUE="">
<input type="button" value="submit" onclick=sumitinfo() >
<INPUT TYPE="reset" NAME="RESET" value="reset">
</form>
</body>
</html>
JavaScript Events
The change in the state of an object is known as an Event.
In html, there are various events which represents that some activity is
performed by the user or by the browser.
When javascript code is included in HTML, js react over these events and
allow the execution.
This process of reacting over the events is called Event Handling.
Thus, js handles the HTML events via Event Handlers
WINDOW
FORM
LOCATION DOCUMENT
….
LINK
ANCHOR
(HTML
ELEMENTS)
FORM
button,textfield
,check boxes
etc
IMPORTANT QUESTIONS
GOOD LUCK