Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
172 views

Javascript 1

JavaScript allows for interactivity on web pages by performing calculations, validating user input, and reacting to user actions. It is an object-based, interpreted programming language that is easy to learn and works across major browsers. JavaScript code can be embedded within HTML pages and executes on the client-side without requiring a connection, allowing for fast interactions. It uses variables, functions, and objects to add dynamic behavior and manipulate page content.

Uploaded by

Ritik
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
172 views

Javascript 1

JavaScript allows for interactivity on web pages by performing calculations, validating user input, and reacting to user actions. It is an object-based, interpreted programming language that is easy to learn and works across major browsers. JavaScript code can be embedded within HTML pages and executes on the client-side without requiring a connection, allowing for fast interactions. It uses variables, functions, and objects to add dynamic behavior and manipulate page content.

Uploaded by

Ritik
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 88

JavaScript

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');

</script> Note the symbol for


</body> line continuation
</html>
JavaScript Statements
<html>
<head><title>My Page</title></head>
<body>
<script language=“JavaScript">

document.write('<h1>This is my first 
JavaScript Page</h1>');

</script> HTML written


</body> inside JavaScript
</html>
JavaScript Popup Boxes
 Alert Box
 An alert box is often used if you want to make sure
information comes through to the user.
 When an alert box pops up, the user will have to click
"OK" to proceed.
<script>
alert("Hello World!")
</script>
JavaScript Popup Boxes - 2
 Confirm Box
 A confirm box is often used if you want the user to
verify or accept something.
 When a confirm box pops up, the user will have to
click either "OK" or "Cancel" to proceed.
 If the user clicks "OK", the box returns true. If the user
clicks "Cancel", the box returns false.
<script>
confirm("Get a message?");
</script>
JavaScript Popup Boxes - 3
 Prompt Box
 A prompt box is often used if you want the user to
input a value before entering a page.
 When a prompt box pops up, the user will have to
click either "OK" or "Cancel" to proceed after entering
an input value.
 If the user clicks "OK“, the box returns the input value.
If the user clicks "Cancel“, the box returns null.
<script>
prompt("What is your favorite color?", "");
</script>
Adding Javascript to HTML
 Events are actions performed by user
 Pressing button, mouse clicks or entering certain data
 Event handlers process events (written in
javascript)
 Display dialog box
 Validate data
 Load and display something
 Interact with any embedded application
 Some events are:
 Onfocus, onclick, onmouseover, keypress, onblur etc.
Example
 <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>
HTML Forms and JavaScript
 JavaScript is very good at processing user input
in the web browser
 HTML <form> elements receive input
 form elements have unique names
 Each unique element can be identified
Naming Form Elements in HTML

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

INE2720 – Web Application Software Development


21
Array Example

<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

Arithmetic Operators Operator

+
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

Assignment Operators Operator Example Is The Same As

= 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

Comparison Operators Operator

==
Description

is equal to
Example

5==8 returns false

=== is equal to (checks for both x=5


value and type)
y="5"

x==y returns true

x===y returns false

!= is not equal 5!=8 returns true

> is greater than 5>8 returns false

< is less than 5<8 returns true

>= is greater than or equal to 5>=8 returns false

<= is less than or equal to 5<=8 returns true


JavaScript Operators - 4

Operator Description Example


Logical Operators && and x=6

y=3

(x < 10 && y > 1)


returns true

|| or x=6

y=3

(x==5 || y==5)
returns false

! not x=6

y=3

!(x==y) returns true


JS Examples -1

Y=20x+12 and x=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.

 click , pressing any key, closing a window,


resizing a window, etc.
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>
onmouseover

 The onmouseover event triggers when you


bring your mouse over any element
Example
•<html>
• <head>
• <script type="text/javascript">

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

• JavaScript provides a way to validate form's data on


the client's computer before sending it to the web
server
Form Validation
 Basic Validation :
 Make sure all the mandatory fields are filled in

 Data Format Validation


 The data that is entered must be checked for
correct form and value
Form
•<html> Validation
• <head>
• <title>Form Validation</title>
• <script type="text/javascript">
• // Form validation code will come here.
• </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
 Validate function

 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}$

Password expression that requires one lower case


letter, one upper case letter, one digit, 6-13 length,
and no spaces. This is merely an extension of a
previously posted expression by Steven Smith
(ssmith@aspalliance.com) . The no spaces is new.
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
Example

Find name of all the students starting with ‘a’


 A+
Brackets
Quantifiers
Metacharacters
Metacharacters
To check a password between 6 to 20 characters which contain at
least one numeric digit, one uppercase, and one lowercase letter

To validate the said format we use the regular expression

^(?=.*\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

You might also like