Javascript 1
Javascript 1
What is JavaScript?
Browsers have limited functionality
Text, images, tables, etc.
JavaScript allows for interactivity
Perform calculations
Validation of input
Browser/page manipulation
Reacting to user actions
A type of programming language (Object Based and
Interpreted)
Easy to learn
Developed by Netscape
Now works in all major browsers
is used in millions of Web pages to improve the design, validate forms,
detect browsers, create cookies, and much more
How Does It Work?
Embedded within HTML page
View source
Executes on client
Fast, no connection needed once loaded
Simple programming statements combined with
HTML tags
Interpreted (not compiled)
No special tools required
Ending Statements With a Semicolon?
Semicolons are optional! Required if you want to put
more than one statement on a single line.
What is Java?
Totally different
A full programming language
Much harder!
A compiled language
Independent of the web
JavaScript Statements
<html>
<head><title>My Page</title></head>
<body>
<script language="JavaScript">
document.write('This is my first
JavaScript Page');
document.write('<h1>This is my first
JavaScript Page</h1>');
<form name="addressform">
Name: <input name="yourname"><br />
Phone: <input name="phone"><br />
Email: <input name="email"><br />
</form>
Forms and JavaScript
document.formname.elementname.value
Thus:
document.addressform.yourname.value
document.addressform.phone.value
document.addressform.email.value
Using Form Data
Personalising an alert box
<form name="alertform">
Enter your name:
<input type="text" name="yourname">
<input type="button" value= "Go"
onClick="window.alert('Hello ' +
document.alertform.yourname.value);">
</form>
JavaScript Variables
Variables are used to store data.
A variable is a "container" for information you
want to store. A variable's value can change
during the script. You can refer to a variable by
name to see its value or to change its value.
Rules for variable names:
Variable names are case sensitive
They must begin with a letter or the underscore
character
strname – STRNAME (not same)
Some variable names
My_variable
Legal
$my_variable
1my_example
_my_variable
@my_variable
My_variable_example
++my_variable
%my_variable Illegal
#my_variable
~my_variable
myVariableExample
Data Types
JavaScript allows the same variable to contain different
types of data values.
Primitive data types
Number: integer & floating-point numbers
Boolean: logical values “true” or “false”
String: a sequence of alphanumeric characters
Composite data types (or Complex data types)
Object: a named collection of data
Array: a sequence of values
Special data types
Null: an initial value is assigned
Undefined: the variable has been created by not yet assigned a
value
18
Numeric Data Types
It is an important part of any programming
language for doing arithmetic calculations.
JavaScript supports:
Integers: A positive or negative number with no
decimal places.
Ranged from –253 to 253
Floating-point numbers: usually written in exponential
notation.
3.1415…, 2.0e11
19
var length = 16; // Number
var lastName = "Johnson"; // String
var cars = ["Saab", "Volvo", "BMW"]; // Array
var x = {firstName:"John", lastName:"Doe"}; // Object
Javascript has dynamic types
var x; // Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String
You can use the JavaScript typeof operator to find the type
of a JavaScript variable:
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof false // Returns boolean
typeof [1,2,3,4] // Returns string
typeof {name:'John', age:34} // Returns object
Array
An Array contains a set of data represented by a
single variable name.
Arrays in JavaScript are represented by the Array
Object, we need to “new Array()” to construct this
object.
The first element of the array is “Array[0]” until the
last one Array[i-1].
E.g. myArray = new Array(5)
We have myArray[0,1,2,3,4].
<script language=“JavaScript”>
Car = new Array(3);
Car[0] = “Ford”;
Car[1] = “Toyota”;
Car[2] = “Honda”;
document.write(Car[0] + “<br>”);
document.write(Car[1] + “<br>”);
document.write(Car[2] + “<br>”);
</script>
You can also declare arrays with variable length.
arrayName = new Array();
Length = 0, allows automatic extension of the length.
Car[9] = “Ford”; Car[99] = “Honda”;
22
JavaScript Operators
+
Description
Addition
Example
x=2
Result
4
y=2
x+y
- Subtraction x=5 3
y=2
x-y
* Multiplication x=5 20
y=4
x*y
/ Division 15/5 3
5/2 2,5
% Modulus (division 5%2 1
remainder)
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
JavaScript Operators – 2
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
JavaScript Operators - 3
==
Description
is equal to
Example
y=3
|| or x=6
y=3
(x==5 || y==5)
returns false
! not x=6
y=3
<script>
x=3
y=20*x+12
alert(y)
</script>
Examples -2
<script>
s1=12
s2=28
total=s1+s2
document.write(“Total is: “,total)
</script>
HW: Write a Javascript for
Calculator
HW: Write a Javascript for Calculator
<html> //function that evaluates the digit and return
<head> result
function solve()
<script> {
//function that display value x=
function dis(val) document.getElementById("result").value
y = eval(x)
{
document.getElementById("result").value = y
document.getElementById("res }
ult").value+=val
//function that clear the display
}
function clr()
{
document.getElementById("result").value = ""
}
</script>
</head>
HW: Write a Javascript for Calculator
<!-- create table -->
<body>
<table border="1">
<tr>
<td colspan="3"><input type="text" id="result"/></td>
<!-- clr() function will call clr to clear all value -->
<td><input type="button" value="c" onclick="clr()"/> </td>
</tr>
<tr>
<!-- create button and assign value to each button -->
<!-- dis("1") will call function dis to display value -->
<td><input type="button" value="1" onclick="dis('1')"/> </td>
<td><input type="button" value="2" onclick="dis('2')"/> </td>
<td><input type="button" value="3" onclick="dis('3')"/> </td>
<td><input type="button" value="/" onclick="dis('/')"/> </td>
</tr>
HW: Write a Javascript for
Calculator
<tr>
<td><input type="button" value="4" onclick="dis('4')"/> </td>
<td><input type="button" value="5" onclick="dis('5')"/> </td>
<td><input type="button" value="6" onclick="dis('6')"/> </td>
<td><input type="button" value="-" onclick="dis('-')"/> </td>
</tr>
</table>
</body>
</html>
Conditional and Repetition Statements
Conditional statements:
if statement - use this statement if you want to execute some code
only if a specified condition is true
if...else statement - use this statement if you want to execute some
code if the condition is true and another code if the condition is false
if...else if....else statement - use this statement if you want to select
one of many blocks of code to be executed
switch statement - use this statement if you want to select one of
many blocks of code to be executed
Repetition structure: four in JavaScript
while
do…while
for
for…in
var r = confirm("Press a button");
if (r == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
if (confirm("Do you agree")) {alert("You agree")}
else{alert ("You do not agree")};
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
for/in statement loops through the properties of
an object:
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x];
}
Next
Functions
Objects and Events
Functions
Functions
A function is a group of reusable code which
can be called anywhere in your program. This
eliminates the need of writing the same code
again and again. It helps programmers in writing
modular codes.
Function Syntax
Example
• <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>
• <input type="button" onclick="sayHello()" value="Say Hello">
• </form>
• <p>Use different text in write method and then try...</p>
• </body>
• </html>
Function Parameters
• <html>
• <head>
• <script type="text/javascript">
• function sayHello(x)
• {
• document.write ("Hello !“ + x);
• }
• </script>
• </head>
• <body>
• <p>Click the following button to call the function</p>
• <form>
• <input type="button" onclick="sayHello(‘jiit’)" value="Say
Hello">
• </form>
• <p>Use different text in write method and then try...</p>
• </body>
• </html>
Function: return Statement
Add return statements to return control or value to
caller
Example
• <html>
• <head>
• <script type="text/javascript">
• function sayHello(name)
• {
• document.write ("Hello there! <br>");
• document.write("name ="+ name +" <br>")
• newname = func2(name)
• document.write("new name "+ newname)
• }
• function func2(name)
• {
• result = name + ' my college'
• return result
• }
• </script>
• </head> <body>
• <p>Click the following button to call the function</p>
• <form>
• <input type="button" onclick="sayHello('jiit')" value="Say Hello">
• </form>
• <p>Use different text in write method and then try...</p>
• </body></html>
Events
Event
JavaScript's interaction with HTML is handled
through events that occur when the user or the
browser manipulates a page.
• function over() {
• document.write ("Mouse Over");
• }
• </script>
• </head>
• <body>
• <p>Bring your mouse inside the division to see the result:</p>
• <div onmouseover="over()" >
• <h2> This is inside the division </h2>
• </div>
• </body>
• </html>
Other Events
Form validation
Form Validation
• Form validation normally used to occur at the
server.
• If the data entered by a client was incorrect or was
simply missing, the server would have to send all
the data back to the client and request that the form
be resubmitted with correct information.
• This was really a lengthy process which used to put a
lot of burden on the server.
function validate() {
if( document.myForm.Name.value == "" )
{ alert( "Please provide your name!" );
return false; }
return true
}
Form Validation Ex1: (Basic)
<html> <head> <title>Form Validation</title>
<script type="text/javascript">
function validate() {
if( document.myForm.Name.value == "" )
{ alert( "Please provide your name!" );
return false; }
return true
}
</script>
</head> <body>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table> </form></body> </html>
Form Validation: Ex-2 (Email)
• <html> <head> <title>Form Validation</title>
• <script type="text/javascript">
• function validate() {
• if( document.myForm.Name.value == "" )
• { alert( "Please provide your name!" ); return false; }
• if( document.myForm.Email.value == "" ) {
• alert( "Please provide your email!" ); return false; }
• return true
• }
• </script>
• </head> <body>
• <form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
• <table cellspacing="2" cellpadding="2" border="1">
• <tr>
• <td align="right">Name</td>
• <td><input type="text" name="Name" /></td>
• </tr>
• <tr>
• <td align="right">Email</td>
• <td><input type="text" name="Email" /></td>
• </tr>
• <tr>
• <td align="right"></td>
• <td><input type="submit" value="Submit" /></td>
• </tr>
• </table> </form></body> </html>
Data field validation
Data Validation
Q: Take an input and check if its is a number or
not.
isNaN(): The isNaN()
Example -3 function determines whether
• <html> <body> a value is an illegal number
• <h1>JavaScript Can Validate Input</h1> (Not-a-Number).
• <p>Please input a number between 1 and 10:</p>
• ID:<input id="numb"> <br>
• <button type=“button" value= "submit" onclick="myFunction()">
• <p id="demo"></p>
• <script>
• function myFunction() { var x, text;
• // Get the value of the input field with id="numb"
• x = document.getElementById("numb").value;
• // If x is Not a Number or less than one or greater than 10
• if (isNaN(x) || x < 1 || x > 100) {
• text = "Input not valid";
• } else {
• text = "Input OK";
• }
• document.getElementById("demo").innerHTML = text;
• }
• </script> </body> </html>
Example 4
Q. Check whether input has email of valid length
or not?
User Name and password
• <html> <body> <script>
• function validateform(){
• var name=document.myform.name.value;
• var password=document.myform.password.value;
• if (name==null || name==""){
• alert("Name can't be blank");
• return false;
• }else if(password.length<6){
• alert("Password must be at least 6 characters long.");
• return false;
• } }
• </script>
• <form name="myform" method="post" action="abc.jsp" onsubmit="return
validateform()" >
• Name: <input type="text" name="name"><br/>
• Password: <input type="password" name="password"><br/>
• <input type="submit" value="register">
• </form> </body> </html>
Example 5
Q. Check if the email has valid format or not?
Email Validation
<script type="text/javascript">
<!--
function validateEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>
Date Validation
<html><body>
<script type="text/javascript">
function validateEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
return false;
}
return( true );
}
</script>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return validateEmail()">
<table cellspacing="2" cellpadding="2" border="1">
<td align="right">Email</td>
<td><input type="text" name="Email" /></td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table> </form></body> </html>
Regular Expressions
Regular Expression to Validate Data
A regular expression is an object that describes a pattern
of characters.
Regular expressions are used to perform pattern-
matching and search-and-replace functions on text.
A regular expression could be defined with the RegExp
() constructor, as follows :
var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;
pattern − A string that specifies the pattern of the regular
expression or another regular expression.
attributes − An optional string containing any of the "g",
"i", and "m" attributes that specify global, case-insensitive,
and multiline matches, respectively.
Brackets
Brackets ([]) have a special meaning when used in
the context of regular expressions. They are used to
find a range of characters.
Quantifiers
The frequency or position of bracketed character
sequences and single characters can be denoted
by a special character.
Each special character has a specific connotation.
The +, *, ?, and $ flags all follow a character
sequence.
Quantifiers
Examples
Metacharacters
Some regular expressions
^[a-zA-Z]\w{3,14}$
The password's first character must be a letter, it
must contain at least 4 characters and no more
than 15 characters and no characters other than
letters, numbers and the underscore may be used
^(?=.*\d).{4,8}$
Password must be between 4 and 8 digits long
and include at least one numeric digit.
Some regular expressions
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,8}$
Password must be at least 4 characters, no more than
8 characters, and must include at least one upper
case letter, one lower case letter, and one numeric
digit.
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{4,8}$
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$.
Question
Write the JavaScript code that uses a regular
expression to validate that the user name
consists of only letters or the blank space
character. Generate an alert message if the name
is incorrect.
Write the JavaScript code that uses a regular
expression to validate that the Email consists
aa@bb.cc where aa, bb, and cc are one or more
alphanumeric characters.
Write the JavaScript code that uses a regular
expression to validate that the optional Telephone
field is in the pattern ddd-ddd-dddd or ddd-dddd
where d is any digit