Chapter3 JavaScript
Chapter3 JavaScript
Lathiya
Assistant Professor
EC Department
GEC Rajkot
Syllabus : 3161012
Syllabus
How Website works?
Client side scripting
Why Use Client-side Programming?
PHP already allows us to create dynamic web pages.
Reference : [Link]
Javascript
• Initially designed for making pages “alive”
• Script can be run inside browser itself.
• Can be executed on browse and server.
• It is safe language when used on browsers.
• Other language (coffee script , typescript ) get “transpired” to
Javascript.
• JavaScript and Java are different programming language.
• NOT related to Java other than by name and some syntactic
similarities
Javascript
• a lightweight programming language ("scripting language")
▫ used to make web pages interactive
▫ insert dynamic text into HTML (ex: user name)
▫ react to events (ex: page load, user click)
▫ get information about a user's computer (ex: browser type)
▫ perform calculations on user's computer (ex: form validation)
▫ a web standard (but not supported identically by all browsers)
Javascript vs Java
• interpreted, not compiled
• more relaxed syntax and rules
▫ fewer and "looser" data types
▫ variables don't need to be declared
▫ errors often silent (few exceptions)
• key construct is the function rather than the class
• contained within a web page and integrates with
its HTML/CSS content
Javascript vs Java
Java JS
Programming Language Scripting Language
Designed by Sun microsystems Designed by Netscape communication
corporation
Designed to used applets, program To improvise web page , client side
Java applets are compiled in class JS is simple text commands written in
files, can be used in web pages HTML file
Java applets visualize in webpage as JS can effect to any part of webpage
box
Object Oriented Language Object Oriented Language
VS Code Shortcuts
• Emmet Abbreviation
• Type following:
• ! ➔ Press Enter
➔ Gives basic minimal html code
• [Link] ➔ Press Enter
▫ ➔ Creates class container
<div class="container"></div>
• Button#click ➔ Press Enter
▫ ➔ Creates ID
<Button id="click"> _________ </Button>
Where to write JS .
<script>
function myFunction()
{
[Link]("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
Way to write JS
External JS :
(Separate File : [Link]))
Console API
[Link](“______________”)
[Link](“ Change line3”)
[Link](“ Error in Line 3”)
[Link]( condition)
• Global Variable
▫ Declared in main script
▫ Can be used in any function.
How to declare variable?
• Keyword : var , let
• DataType can be automatically defined (string ,
number, boolean etc ) as value assigned to it.
• Example:
▫ var m1 = 10
▫ var f = 20.34
▫ var s1 = “Hello”
▫ var s2 = ‘GECR’
▫ var d = null
▫ var df = undefined
▫ var sw = true
▫ var arr = [34 , 56 , 9 ]
DataTypes
• Two Types:
▫ Primitive data type :
Undefined, null, number, string, boolean, symbol
▫ Reference/Special data type
Arrays, Objects
Primitive Data Types
• Numbers
▫ var m1 = 10
▫ var f = 20.34
• String
▫ var s1 = “Hello”
▫ var s2 = ‘GECR’
• Boolean
▫ var a = true
▫ var b = false
• Undefined
▫ If value is not given to variable or value is undefined.
▫ var f = undefined
▫ var z2; // only declared variable is undefined
• NULL
▫ var K1 = null // different from undefined
Reference/Special Data Types
• Objects
▫ var marks = { ravi : 10 ,
ronak : 20.30,
raj : 98
};
• Arrays:
▫ var z1 = [1, 2, 34, 37, 89]
▫ var z2 = [1 , 2, “ravi”, 43, 23]
• Question:
▫ Find difference and similarity between objects and array
▫ Find where to use objects and array
Operators
• Arithmetic (+, - , *, / , %)
• Conditional / comparision ( >, >=, <, <= , ==, !=)
▫ Results in True or False
• Logical (&&, ||, !)
▫ Results in True or False
• Bitwise Operator ( &, | , ^, ~)
• Ternary Operator(?:)
▫ C = (condition)?_True_Expression_: _False_Expression_
• Assignment Operator ( = , +=, *= , -=, /=)
• Shift Operator ( << , >>)
• Increment/Decrement ( ++ , -- , Pre, Post)
Bitwise Operator
50 = 0011 0010 50 = 0011 0010
78 = 0100 1110 78 = 0100 1110
---------------------- ----------------------
& = 0000 0010 = 2 ^ = 0111 1100 = 124
50 = 0011 0010
78 = 0100 1110
----------------------
| = 0111 1110 = 126
Bitwise Operator
50 = 0011 0010
----------------------
~ = 1100 1101 = 205
51 = 0011 0011
51 1’s comp = 1100 1100
51 2’s comp = 1100 1101 = (-51) = (205)
Ternary Operator
a = 50
B = 78
c = ((a<100)||(b>50))?(a+b/2):(a+b*2)
= ( True || True) ? (a+b/2):(a+b*2)
= True ? (50 + 78/2): ________
= 50 + 78/2
= 50 + 39
= 89
Assignment Operator
Operation Shorthand notation
C=C+1 C += 1
C = c -1 C -= 1
C = C*10 C *= 10
C = C & 30 C &= 30
C = C | 30 C |= 30
C=A+B
Shift Operator
P1DIR = (1<<3) = 0000 1000
0x80 = 1000 0000
P1DIR |= (1<<3) (0x80>>2) = 0010 0000
P1DIR = P1DIR | (1<<3)
var c1 = avg(5,15)
var c2 = avg(60, 50)
If Condition
• Simple if
• if-else statement
• Ladder if-else statement
• Nested if-else statement
If Condition
if( a > 16 && a<21) if( a <= 12) {
{ [Link](“Kid”);
[Link](“Teenage”); }
} else if(a>12 && a <=21){
[Link](“Teenage”);
if( a > 16) }
{ else if(a>21 && a <=35){
[Link](“Teenage”); [Link](“Young”);
} }
else
{ else if(a>35 && a <=50){
[Link](“Kid”); [Link](“Mature”);
} }
else {
[Link](“Aged”);
}
Loop
• For Loop: • Break
▫ for • If condition satisfy,
▫ foreach stop iterating.
▫ for…in • Continue
▫ for …of • If condition satisfy,
• While Loop: that part will be
• do-while Loop: skipped
Loop (For)
var arr = [10,20,30,40];
let sum = 0;
for (var i=0; i<[Link] ; i++)
{
sum = sum + arr[i];
}
[Link](sum);
Output : 100
Loop (Foreach)
var numbers = [10,20,30,40];
let sum=0;
[Link](myfunction);
[Link](sum);
function myfunction(item)
{ sum = sum + item; } Output : 100
}
</script>
Math Library
[Link](M)
• M = [Link] ➔ 3.141592653589
• M = [Link](10.2) ➔ 10
• M = [Link](10.2) ➔ 11
• M = [Link](10.2) ➔ 10
• M = [Link](16) ➔ 4
• M = [Link](27) ➔ 3 (cube root)
• M= Math.log10(100) ➔ 2
Array Methods
var arr = [34, 56, 18 , “hello”, 3.5];
var a2 = [2, 3]
Use [Link]( ) to see output
[Link] ➔ 5
[Link]( ); ➔ [34, 56, 18, “hello”]
[Link](“hi”); ➔ [34, 56, 18 , “hello”, 3.5, “hi”]
[Link](); ➔ [56, 18 , “hello”, 3.5];
[Link](89); ➔ [89, 34, 56, 18 , “hello”, 3.5];
[Link]( ) ➔ "34,56,18,hello,3.5“
[Link]( ) ➔ [18, 3.5, 34, 56, "hello"]
[Link](‘*’) ➔ "34*56*18*Hello*3.5“
[Link](a2) ➔ [34, 56, 18 , “hello”, 3.5, 2, 3]
[Link]() ➔ [3.5, “hello”, 18, 56, 34]
Splice( ) ➔Adds new items
Array Methods Slice( ) ➔ slices piece of array
function myfunction(num)
{
return (num*10);
}
Output : Array(4) [40, 90 , 160, 250]
filter( ) ➔ create new array of
Array Methods elements if element pass the test
provided in function
Do not change original array
var numbers = [14, 19, 16, 25, 33, 10];
var above18arr = [Link](myfunction)
[Link](above18arr);
function myfunction(num)
{
if(num>18) Alternate way :
return true; function myfunction(num)
else {
return false; return (num >= 18);
} }
<script>
var person {
firstname : “Punit”
lastname : “Lathiya”
fullname : function()
{ return ([Link] + “ ” + [Link]) }
};
var m1 = [Link](person)
var m2 = [Link](person)
[Link](m1)
[Link](m2)
</script>
Output : Array(3) [“firstname” ,”lastname”, “age”]
Array(3) [“Punit”, “Lathiya”, 36]
Objects and its method
<script>
function person(fname, lname, age, Xcolor, len)
{
[Link] = fname;
[Link] = lname;
[Link] = age;
[Link] = Xcolor;
[Link] = len;
}
[Link] ➔ 34
[Link](“GECR”) ➔ 16
[Link](“GECR”) ➔ 22
[Link](0,3) ➔ Hel
[Link](“we”, “wii”) ➔ Hello wii ….
[Link]( )
[Link]( )
[Link]( )
[Link]( )
[Link]( )
[Link]
Document Object Model (DOM)
• With the HTML DOM, JavaScript can access and
change all the elements of an HTML document.
• When a web page is loaded, the browser creates a
Document Object Model of the page.
Document Object Model (DOM)
• With the object model, JavaScript gets all the power it needs
to create dynamic HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page
Document Object Model (DOM)
• Objects : All HTML Elements
▫ <h1> , <p> , <form>, <table>, id , div, class
• Property: value of HTML Element (that you can get or set)
▫ innerHTML, [Link], [Link] , height, width, src etc.
• Method: Action to do (like Add/delete/modify)
▫ getElementById, getElementByTagName etc
<html>
<body>
<p id="demo"> </p>
<script>
[Link]("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
Document Object Model (DOM)
• Method to find HTML Elements:
[Link](id)
[Link](name)
[Link](name)
[Link]('h1')
[Link]('h1')[0].[Link]= "39pt"
[Link]('h1')[0].[Link] = "red“
[Link]('h1')[0].[Link] = "Yellow“
[Link]('h1')[0].[Link] = "hidden“
[Link]('h1')[0].[Link] = "None"
Document Object Model (DOM)
• Adding or Deleting Elements:
[Link](element)
[Link](element)
[Link](element)
[Link](new, old)
[Link](text)
Document Object Model (DOM)
Let k = [Link](‘div’);
let fg = [Link](‘p’)
[Link] = “Hello Vithlani Sir”
[Link] = “blue”
k[0].appendChild(fg);
k[0].replaceChild(fg2, fg)
HTML/JS Events
• HTML events are "things" that happen to HTML elements.
• When JavaScript is used in HTML pages, JavaScript can
"react" on these events.
• When a user clicks the mouse
• When a web page has loaded
• When an image has been loaded
• When the mouse moves over an element
• When an input field is changed
• When an HTML form is submitted
• When a user strokes a key
• Method:
▫ <element event='some JavaScript'>
HTML/JS Events
Events Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
The user moves the mouse away from an HTML
onmouseout
element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
Wheel The mouse wheel rolls up or down over an element
Mousedown The mouse button is pressed over an element
[Link]
HTML/JS Events Examples
<button onclick="[Link]('demo').innerHTML = Date()">The
time is?</button>
• chess = 'He played the King in A8 and she moved her Queen in C2.’
mypattern= /\w\d/g
[Link]([Link](mypattern))
Syntax: /pattern/modifier
Modifier : g Global
Regular Expression (RegEx)
• Example-3: count vowels in the string
• mystr = ‘The quick brown fox jumps over the lazy dog’
mypattern= /[AEIOUYaeiouy]/g
[Link]([Link](mypattern).length)
Output : 12
Syntax: /pattern/modifier
Expression
(with brackets)
[abc] Find any characters from bracket
[^abc] Find any characters NOT between brackets
[0-9] Find any digits between brackets
[^0-9] Find any digits NOT between brackets
(x|y) Find alternatives from x or y
Regular Expression (RegEx)
• /pattern/modifier
Metacharacters
\w Find word character
\W Find non-word character
\d Find Digit character
\D Find Non-Digit character
\s Find White Space
\b Find a match at the beginning/end of a word, beginning
like this: \bHI, end like this: HI\b
• [Link](string) Output:
True/False
let text = "The best things in life are free";
let pattern = /e/; Result : True
let result = [Link](text);
Output:
• [Link](pattern) Integer(Position)
Server
Browser Active Server-side
POST or GET Code
Form
Response Page
Validation
Validation
Request Result Validation
JavaScript
Validation Code Update
Database
Client-side Server-side
Validation Validation
Form validation
• JS provides a way to validate form’s data on client
computer before sending it to server.
• Two Function:
▫ Basic Validation:
Check whether data filled in each field.
Done using loop through each field in form and check
data
▫ Data Format Validation:
Check whether entered data is in correct form and
value.
Need to add logic test.
As appearing on the As appearing in the JavaScript
screen Document Object Model
Window window
HTML document
A form
document
A text field
A checkbox
form
text checkbox
User Performs Some Action
Such as clicking,
typing, etc.
Find Object Corresponding
To User Operation
Yes
Event Handler Execute JavaScript for
Defined? the Event Handler
Done
Basic Validation
<html>
<head>
<title>Submit Example</title>
<script> JavaScript code in next slide
</script>
Temporary
</head> action URL for
testing
<body>
<form id="myForm" method="get" action="javascript:alert('submitted')"
onsubmit="return check(this);" >
<input type="text" name="t1" >
<input type="checkbox" name="c1" value="c1" >
<input type="submit" >
</form>
</body>
</html>
Form Validation
The alert function is built in
<script language="JavaScript"> • The alert function pops up a confirmer
box with the given text and an OK
function check(form) button.
{
if([Link] == "") • This is an example to illustrate the
{ coding technique. In good design
alert("The text field is empty."); practice, a more detailed, user-friendly
return false; message might be given.
}
The check function returns false.
if(! [Link])
{ • This tells the browser to not continue
alert("The checkbox is not checked."); with the submit.
return false;
}
return true;
}
</script>
This tests if the checkbox is checked or not.
Form Validation • The checked attribute is a Boolean.
• The ! is the NOT operator.
<script language="JavaScript"> • It is, of course, pointless to have a single
checkbox that you require to be checked
function check(form)
{ • Normally, there would be multiple
if([Link] == "") checkboxes and you would verify that at least
{ one of them is checked – or whatever you
alert("The text field is empty."); wish.
return false;
}
popup alert box and the function returns
if(! [Link]) false to indicate that the submit should
{ not occur.
alert("The checkbox is not checked.");
return false;
} The check function returns true if
return true; everything is OK. This causes the submit
} to actually occur.
</script>
Email ID Validating
• Validating email is a very important point while
validating an HTML form.
• An email is a string (a subset of ASCII characters)
separated into two parts by @ symbol.
• Personal_info@domain_name
• Max : 64 character @ 256 characters
• Personal Info:
▫ Alphabets (A-Z, a-z) and Digits (0-9)
▫ Special Characters : !, #,$,%,^, fullstop(.) , {, }, +
▫ Period(Fullstop) must not be last characters
• Domain:
▫ com, org, in, edu etc
Email ID Validating
• Example of valid email id
▫ mysite@[Link]
▫ [Link]@[Link]
▫ mysite@[Link]
Email ID Validating
function ValidateEmail(inputText)
{
// var mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
// varmailformat = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/;
if([Link](mailformat))
{
alert("Valid email address!");
[Link]();
return true;
}
else
{
alert("You have entered an invalid email address!");
[Link]();
return false;
}
}
Meaning of pattern
"^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$
Pattern Meaning
^[\\w-_\.] ^ : Check
\\w : word starting with A-Z,a-z,0-9
It can also be
Underscore(_), Hyphen(-) , period(.)
*[\\w-_\.] * : Next series of characters
Same as above
\@[\\w]\.+ Next section begins with @
Following with word (\\w) and atleast
one period/dot (.)
[\\w] +[\\w]$ Some word (\\w) after dot(.)
Last part checks : Last character is
word.
Validating Phone Number
• Checking 10 digit Mobile number without
comma, punctuation mark and no + sign in front.
• Ex : 9999874585
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if(([Link](phoneno))
return true;
else
{
alert(“Wrong Mobile Number");
return false;
}
}
function phonenumber(inputtxt) { var phoneno = /^\d{10}$/; if(([Link](phoneno)) { return true; } else { alert("message"); return false; } }
if(([Link](phoneno))
return true;
else
{
alert("message");
return false;
}
}
if([Link] != 10 || isNaN([Link].
value) || [Link] == "")
{
[Link]("incoreect input")
check = false;
}
else
{
[Link]("correct mobile number")
check = true;
}
return check;*/
Exercise
• Validate IP Address
▫ [Link]
▫ [Link]
• Validate Entered Password
▫ Only 8-17 characters, At least one special characters
▫ No white space
▫ 1-255
Thank You