javascript tutorial mickey nguyen - …h2>i am using h2, this font should smaller compare to h1...

58
JavaScript Tutorial Mickey Nguyen 1 JavaScript Tutorial Written by: Mickey Nguyen (linkedin: [email protected]) 2015 1 Introduction .......................................................................................................................................... 3 1.1 Hello world example1 ................................................................................................................... 3 1.2 Hello world example2 ................................................................................................................... 8 2 Javascript output................................................................................................................................. 11 2.1 Using document.write() .............................................................................................................. 11

Upload: dinhtu

Post on 21-Apr-2018

222 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

1

JavaScript Tutorial

Written by: Mickey Nguyen

(linkedin: [email protected])

2015

1 Introduction .......................................................................................................................................... 3

1.1 Hello world example1 ................................................................................................................... 3

1.2 Hello world example2 ................................................................................................................... 8

2 Javascript output ................................................................................................................................. 11

2.1 Using document.write() .............................................................................................................. 11

Page 2: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

2

2.2 Using innerHTML ......................................................................................................................... 12

2.3 Using window.alert() ................................................................................................................... 13

3 Data types and Syntax ......................................................................................................................... 15

4 String ................................................................................................................................................... 17

5 Data Types Conversion........................................................................................................................ 20

6 Array Object data type ........................................................................................................................ 23

7 Typeof ................................................................................................................................................. 25

8 Function .............................................................................................................................................. 27

8.1 Example1: calling external javascript code ................................................................................. 27

8.2 Exampl2: implement javascript code inside html <head> Tag ................................................... 28

8.3 Example3: implement javascript code inside html <body> Tag ................................................. 29

9 Button Event ....................................................................................................................................... 31

10 Math .................................................................................................................................................... 33

11 Date, Time ........................................................................................................................................... 35

12 Compare &&, ||, != ............................................................................................................................. 36

13 If-else if-else ........................................................................................................................................ 39

14 Switch case .......................................................................................................................................... 41

15 For,while,do while loop ...................................................................................................................... 42

16 Break, continue ................................................................................................................................... 44

17 RegExpression ..................................................................................................................................... 46

18 Error handling try-throw-catch, text box input .................................................................................. 48

19 JSON to javascript ............................................................................................................................... 51

20 JSON .................................................................................................................................................... 53

20.1 Quick review about XML ............................................................................................................. 54

20.2 Example of JSON ......................................................................................................................... 54

20.3 Example of Convert JSON to Javascript object. .......................................................................... 56

Page 3: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

3

1 Introduction

This is a high level principle concept of JavaScript.

I am going to use Eclipse to compile and run Javascript (js).

There are two way to implement and run javascript code:

- 1st way, implement javascript code inside html form.

- 2nd way, calling external javascript code : at first define javascript code externally. then create

html form and calling that external javascript to display the result in the web

1.1 Hello world example1 I am going to show you 1st way of writing and run javascript inside html form. Here are steps how to

create your first Javascript to say “Hello world”. In this example we write Javascript inside html form.

So, in the html file where you see <script> Tag , inside this Tag is javascript code.

We are going to use Eclipse IDE to write and run

Create a static web project:

File->New->Project->Web->Static Web Project

Page 4: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

4

Give it a name “com.mickey.webproject”

Page 5: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

5

Finish

Page 6: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

6

Create HTML file, Right click on WebContent->New->Other->Web->HTML File, name it

“section1_1.html”

Now, create <script> Tag so you can write javascript inside this html file, update this html file to this

<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <!-- This is syntax for comment just like // --> <!-- This is script Tag so you can write javascript code inside this Tag --> <script> document.write("Mickey, Hello world!"); </script> </body>

Page 7: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

7

</html>

Save it, then run it, Right click on section1_1 file->Open With->Web Browser

Page 8: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

8

So, make sure you understand that we use HTML form to display the run output. Your javascript code just only one line document.write("Mickey, Hello world!");

All other lines of code are html code.

Remember this: in html file where you see the <script> Tag, inside <script> Tag that where you write javascript code. All the other codes are HTML code. HTML form is for display purpose. Beside display purpose, you can define things such as id in HTML Tag

and use it in javascript code. As you go on with examples, you will see how to define id in HTML and use

javascript code together

1.2 Hello world example2 This example I am going to show you 2nd way to write javascript externally, then call javascript code

inside html form.

Page 9: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

9

Right click on WebContent->New->File, name it “Hello1_2.js”, don’t forget to have extension js

Add this javascript code to Hello1_2.js

//function to return a string //every function has to have function keyword in front of it. function SayHello() { return "Mickey, Hello world"; }

Create section1_2.html to call function SayHello inside Hello1_2.js

<!DOCTYPE html> <html>

Page 10: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

10

<head> <!-- Create script Tag to specify what javascript you try to run --> <script type="text/javascript" src="Hello1_2.js"></script> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <!-- This is script Tag so you can write javascript code inside this Tag --> <!-- create a script Tag to write javascript to call function from Hello.js --> <script> document.write(SayHello()); </script> </body> </html>

Save and run it

Page 11: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

11

2 Javascript output There are a few way to print out out in javascript

2.1 Using document.write() Create a new html file under WebContent, name it “section2_1.html”, add these codes

<!DOCTYPE html> <html> <body> <h2>I am using h2, this font should smaller compare to h1</h2> <p>This is a paragraph, whatever you want to see</p> <script> document.write(5 + 6); </script> </body> </html>

Save section2_1.html and run it.(Right click on the file->Open with Web browser)

Page 12: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

12

2.2 Using innerHTML Create section2_2.html code with these codes

<!DOCTYPE html> <html> <body> <h2>I am using h2, this font should smaller compare to h1</h2> <p>This is a paragraph, whatever you want to see</p> <!-- define id in html code and use it in javascript code --> <!-- base on id number, it will act accordingly in javascript code --> <p id="id1">with this id, do something inside the script</p> <p id="id2">with this id, do another thing inside the script</p> <script>

Page 13: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

13

<!-- base on id number we do different thing --> document.getElementById("id1").innerHTML = 5 + 6; document.getElementById("id2").innerHTML = "Yes, 2nd ID, we print this out"; </script> </body> </html>

Save section2_2.html, run it

2.3 Using window.alert() Create section2_3.html with these codes

<!DOCTYPE html> <html> <body> <h2>I am using h2, this font should smaller compare to h1</h2>

Page 14: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

14

<p>This is a paragraph, whatever you want to see</p> <script> window.alert(5 + 6); </script> </body> </html>

Page 15: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

15

3 Data types and Syntax There are 3 primitive data types: String, number, and Boolean. Just use “var” keyword in front of your

variable name. int,float,double just a number. Number is number, in Javascript there is no distinction

between numbers.

Use \ to continue your statement at new line

String can use either “ “ or ‘ ‘, variable name is case sensitive, var is generic data type, it cans hold

anything such as int, float, string, object,….

Can use either <!-- this --> or // or /* this */

Create section3.html with these codes

<!DOCTYPE html> <html> <body> <h1>JavaScript Statements</h1> <p>Statements are separated by semicolons.</p> <p>The variables x, y, sum it up and display:</p> <p>The variables firstname,lastname, fullname are strings</p> <!-- base on id number it does right things down there --> <p id="id1"></p> <p id="id2"></p> <p id="id3"></p> /* can also use div Tag to define id */ <div id="id4"></div> <div id="id5"></div> <div id="id6"></div> <script> <!-- x,y,z are numbers --> var x = 5; var y = 6; var z = x + y; <!-- var can be anything int, double,float,string, object,... --> var i = 9.99999; var j = 5.55; <!-- can use Math.floor(number), Math.round(number) too --> <!-- k is a string now and it has a float with 3 decimal point --> var k = (i + j).toFixed(3); <!-- var for string --> var firstname = "Mickey"; <!-- use \ to continue next line --> var sonName = "Patrick \ Nguyen";

Page 16: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

16

<!-- double quote or single quote doesn't matter --> var lastname ='Nguyen'; var fullname = firstname + " " + lastname; <!-- if you try to operate mix data type string and number, --> <!--and if you begin with a string, then --> <!--it will consider the rest of them are all strings --> var mixdatatype1 = "4" + x + y; <!-- if you try to operate mix data type string and number, --> <!--and if you begin with number, then --> <!--it will operate with number until it see string --> var mixdatatype2 = x + y + "7"; <!-- base on id number it does right thing right here --> document.getElementById("id1").innerHTML = z; document.getElementById("id2").innerHTML = k; document.getElementById("id3").innerHTML = fullname; document.getElementById("id4").innerHTML = "Son name: "+ sonName; document.getElementById("id5").innerHTML = mixdatatype1; document.getElementById("id6").innerHTML = mixdatatype2; </script> </body> </html>

Save section3.html and run it

Page 17: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

17

4 String There are many APIs that String object can provide to you.

Create section4.html with these codes

<!DOCTYPE html> <html> <body> <p>I am going to show a few useful API that string object provide to us</p> <!-- defined id, base on id number it will act accordingly in the script --> <p id="id1"></p> <p id="id2"></p> <p id="id3"></p> <p id="id4"></p> <p id="id5"></p>

Page 18: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

18

<p id="id6"></p> <p id="id7"></p> <p id="id8"></p> <p id="id9"></p> <p id="id10"></p> <p id="id11"></p> <p id="id12"></p> <p id="id13"></p> <p id="id14"></p> <script> var mystr = "Mickey Nguyen is a software engineer. He is a good guy"; <!-- length --> var len = mystr.length; <!-- search for index of software engineer--> var index = mystr.search("software engineer"); <!-- search and copy from software engineer to all the way ending --> var substr =mystr.substring(index); <!-- replace software engineer to hardware engineer --> mystr = mystr.replace("software engineer","hardware engineer"); <!-- to upper case or to lower --> var toupperstr = mystr.toUpperCase(); <!-- compare two strings --> var str1 = "Mickey" var str2 = new String ("Mickey"); <!-- string to int --> var number9 = "9"; <!-- in str format --> var numInt = parseInt(number9); <!-- int to string --> var numStr = numInt.toString(); <!-- another way convert int to string --> var numStr2 = String(11); <!-- Boolean to String --> var myFlag = String(true); var ans =false; <!-- convert string back to Boolean --> if (Boolean(myFlag)) { ans = true; } <!-- Using single or double quote --> var nameSignleQuote = '"What is your name?"'; var nameDoubleQuote = "'Who am I?'"; var combineThem = nameSignleQuote + " " + nameDoubleQuote; <!-- acting on each id number --> document.getElementById("id1").innerHTML = mystr +", len: "+len; document.getElementById("id2").innerHTML = "substr: " + substr;

Page 19: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

19

document.getElementById("id3").innerHTML = "new mystr: " + mystr; document.getElementById("id4").innerHTML = "To upper: " + toupperstr; document.getElementById("id5").innerHTML = (str1 === "Mickey"); <!-- str2 compare to Mickey false because it is an object --> document.getElementById("id6").innerHTML = (str2 === "Mickey"); document.getElementById("id7").innerHTML = "Str1 is " + typeof str1 + "<br>" + "Str2 is " + typeof str2 ; <!-- both str1 and str2 have value Mickey but they are different data type --> document.getElementById("id8").innerHTML = (str1 === str2); document.getElementById("id9").innerHTML = numInt +1; document.getElementById("id10").innerHTML = numStr +8; document.getElementById("id11").innerHTML = parseInt(numStr2) +8; document.getElementById("id12").innerHTML = myFlag; document.getElementById("id13").innerHTML = ans; document.getElementById("id14").innerHTML = combineThem; </script> </body> </html> Save and run it

Page 20: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

20

5 Data Types Conversion Here is example of conversion between data type

Create Section5.html

<!DOCTYPE html> <html> <body> <p>I am going to show a few data types conversion</p> <!-- defined id, base on id number it will act accordingly in the script --> <p id="id1"></p> <p id="id2"></p> <p id="id3"></p> <p id="id4"></p> <p id="id5"></p> <p id="id6"></p> <p id="id7"></p> <p id="id8"></p> <p id="id9"></p>

Page 21: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

21

<p id="id10"></p> <script> <!-- string to int --> <!-- it is in str format --> var number9 = "9"; <!-- convert to int type --> var num9Int = parseInt(number9); <!-- string to float --> var numFloatStr = "9.99"; var numFloat = parseFloat(numFloatStr); <!-- use Number to convert string to number --> var num1= Number("19"); var num2 = Number("19.99"); <!-- use toFixed to limit number of decimal --> var myfloat1 = 12.12345; myfloat1.toFixed(3); <!-- it is a string now --> <!-- use toPrecision to limit total number of digits --> var myfloat2 = 13.156; myfloat2.toPrecision(7); <!-- it is a string now, and it should be total 7 digits 13.15600 --> var myfloat3 = 13.1567; myfloat3.toPrecision(4); <!-- it is a string now, and it should be total 4 digits 13.16 --> <!-- int to string --> var myNum = 12; var numStr = myNum.toString(); <!-- another way convert int to string --> var numStr2 = String(11); <!-- Boolean to String --> var myFlag = String(true); var ans =false; <!-- convert string back to Boolean --> if (Boolean(myFlag)) { ans = true; } <!-- acting on each id number --> document.getElementById("id1").innerHTML = num9Int + 1; <!-- 10 --> document.getElementById("id2").innerHTML = numFloat +0.01; <!-- 10 --> document.getElementById("id3").innerHTML = num1 + 1; <!-- 20 -->

Page 22: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

22

document.getElementById("id4").innerHTML = num2 + 1; <!-- 20.99 --> document.getElementById("id5").innerHTML = myfloat1.toFixed(3); <!-- 12.123 --> document.getElementById("id6").innerHTML = myfloat2.toPrecision(7); <!-- 13.15600 --> document.getElementById("id7").innerHTML = myfloat3.toPrecision(4); <!-- 13.16 --> document.getElementById("id8").innerHTML = numStr +1; <!-- 121 --> document.getElementById("id9").innerHTML = numStr2 +1; <!-- 111 --> document.getElementById("id10").innerHTML = ans; <!-- true --> </script> </body> </html>

Save and run it

Page 23: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

23

6 Array Object data type Create Section6.html with these codes

<!DOCTYPE html> <html> <body> <p>Array of int and array of string example</p> <p>Also object data type example</p> <!-- defined id, base on id number it will act accordingly in the script --> <p id="id1"></p> <p id="id2"></p> <p id="id3"></p> <p id="id4"></p> <p id="id5"></p> <p id="id6"></p> <script> <!-- Array of int --> var numArray = [3,4,5]; <!-- Empty array, then you can add anything to it --> var array2 = []; array2[0] = 50; array2[1] = "Mickey" <!-- you can push in next element, too --> array2.push("Patrick"); array2.push(33.33); <!-- Array of String --> var cars = ["Toyota","Honda","Nissan"]; <!-- object data type --> var mickeyInfo = { firstName : "Mickey", lastName : "Nguyen", age : 50, weight : 199.99 }; <!-- use standard for-loop to loop thru numArray array --> function PrintArrayInt() { var text = ""; <!-- loop thru array --> var len = numArray.length; var i; for (i = 0; i < len; i++) { text += numArray[i] + "<br>"; } return text; }

Page 24: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

24

<!-- use for-in to Loop thru mickeyInfo object --> function PrintMickeyInfo1() { var text = ""; var item; <!-- loop thru object --> for (item in mickeyInfo) { text += mickeyInfo[item] + "<br>"; } return text; } <!-- other way to loop thru object --> function PrintMickeyInfo2() { var text = ""; var item; text += mickeyInfo.firstName + "<br>"; text += mickeyInfo.lastName + "<br>"; text += mickeyInfo.age + "<br>"; text += mickeyInfo.weight + "<br>"; return text; } <!-- call PrintArrayInt function. --> document.getElementById("id1").innerHTML = PrintArrayInt(); <!-- first index of cars --> document.getElementById("id2").innerHTML = cars[0]; document.getElementById("id3").innerHTML = array2[0] + ", " + array2[1] + ", " + array2[2] + ", " + array2[3]; document.getElementById("id4").innerHTML = mickeyInfo.firstName + " " + mickeyInfo.lastName + " is " + mickeyInfo.age + " years old," + " and " + mickeyInfo.weight + " lbs"; <!-- call PrintMickeyInfo --> document.getElementById("id5").innerHTML = PrintMickeyInfo1(); document.getElementById("id6").innerHTML = PrintMickeyInfo2(); </script> </body> </html>

Save and run it

Page 25: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

25

7 Typeof Use typeof operator to check data type of variable

Create section7.html with these codes

<!DOCTYPE html> <html> <body> <p>The typeof operator returns the type of a variable or an expression.</p> <p id="id1"></p>

Page 26: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

26

<script> var name = "Mickey"; var pi = 3.14; var flag = true; var arrayInt = [1,2,3,4]; var mickeyInfo = {name:'Mickey', age:50} document.getElementById("id1").innerHTML = typeof (name) + "<br>" + typeof (pi) + "<br>" + typeof (flag) + "<br>" + typeof (arrayInt) + "<br>" + typeof (mickeyInfo); </script> </body> </html>

Save and run it.

Page 27: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

27

8 Function

8.1 Example1: calling external javascript code Create Hello8_1.js with these codes

//function to return a string //every function has to have function keyword in front of it. function MickeySayHello() { return "Mickey, Hello world!!!"; } function PatrickSayHello() { return "Patrick, Hello world!!!"; } function SarahSayHello() { return "Sarah, Hello world!!!"; }

Create Section8_1.html with these codes

<!DOCTYPE html> <html> <head> <!-- Create script Tag to specify what javascript you try to run --> <script type="text/javascript" src="Hello8_1.js"></script> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <!-- define id in html code and use it in javascript code --> <!-- base on id number, it will act accordingly in javascript code --> <p id="id1">with this id, do something inside the script</p> <p id="id2">with this id, do another thing inside the script</p> <p id="id3">with this id, do another thing inside the script</p> <!-- Here is script Tag to write javascript code --> <script> <!-- baseon id number it will call differently --> document.getElementById("id1").innerHTML = MickeySayHello(); document.getElementById("id2").innerHTML = PatrickSayHello(); document.getElementById("id3").innerHTML = SarahSayHello(); </script> </body> </html>

Save it,run it

Page 28: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

28

8.2 Exampl2: implement javascript code inside html <head> Tag

You can have <script> Tag inside <head> Tag

create section 8_2.html with these codes <!DOCTYPE html> <html> <head> <!-- define script tag and implement javascript code here --> <script type="text/javascript"> function SarahHello() { return "Sarah Hello JavaScript"; } function ChauHello() { return "Chau Hello JavaScript"; } </script> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <!-- define id in html Tag and use it in javascript code later --> <p id="id1">Whatever you want to display or just left it empty</p> <p id="id2"> </p> <script> <!-- Base on id number, we call different thing --> document.getElementById("id1").innerHTML = SarahHello(); document.getElementById("id2").innerHTML = ChauHello(); </script> </body> </html>

Save and run it

Page 29: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

29

8.3 Example3: implement javascript code inside html <body> Tag

Last example I define javascript code inside <head> Tag, in this example, I have all javascript code inside <body> Tag. Create section8_3.html with these codes <!DOCTYPE html> <html> <head> <!-- define script tag and implement javascript code here --> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <!-- define id in html Tag and use it in javascript code later --> <p id="id1">Whatever you want to display or just left it empty</p> <p id="id2"> </p> <script> function SarahHello() {

Page 30: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

30

return "Sarah Hello JavaScript"; } function ChauHello() { return "Chau Hello JavaScript"; } <!-- Base on id number, we call different thing --> document.getElementById("id1").innerHTML = SarahHello(); document.getElementById("id2").innerHTML = ChauHello(); </script> </body> </html>

Save run it

Page 31: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

31

9 Button Event Create a button in html form, when user click on it, it trigger a callback event

Create section9.html with these codes

<!DOCTYPE html> <html> <body> <p>Click on the button to see my name</p> <script> function MyName() { return "My name is Mickey Nguyen"; } </script> <p id="id"></p> <!-- button Tag is a keyword, onclick is attribute name --> <button onclick="getElementById('id').innerHTML= MyName()">What is your name?</button> </body> </html>

Page 32: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

32

Page 33: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

33

10 Math

Some maths APIs

Create section10.html with these codes

<!DOCTYPE html> <html> <body> <p>Showing some of math APIs.</p> <!-- defined id, base on id number it will act accordingly in the script --> <p id="id1"></p> <p id="id2"></p> <script> <!-- random number between 0 and 1 -->

Page 34: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

34

var num = Math.random(); <!-- random number between 0 and 99 --> <!-- use floor or ceil or round to round up or down --> var num2 = Math.floor(Math.random() * 100); <!-- acting on each id number --> document.getElementById("id1").innerHTML = "Random number 0..1: "+ num; document.getElementById("id2").innerHTML = "Random number 0..99: "+ num2; </script> </body> </html>

Save and run it

Page 35: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

35

11 Date, Time

Create section11.html with these code

<!DOCTYPE html> <html> <body> <p id="id1"></p> <p id="id2"></p> <p id="id3"></p> <p id="id4"></p> <p id="id5"></p> <p id="id6"></p> <p id="id7"></p> <p id="id8"></p> <p id="id9"></p> <script> var d = new Date(); document.getElementById("id1").innerHTML = d.toString(); document.getElementById("id2").innerHTML = d.getDate(); document.getElementById("id3").innerHTML = d.getDay(); <!-- 0 .. 6 --> document.getElementById("id4").innerHTML = d.getFullYear(); document.getElementById("id5").innerHTML = d.getMonth(); <!-- 0 .. 11 --> document.getElementById("id6").innerHTML = d.getHours(); <!-- 0 .. 23 --> document.getElementById("id7").innerHTML = d.getMinutes(); <!-- 0 .. 59 --> document.getElementById("id8").innerHTML = d.getSeconds(); <!-- 0 .. 59 --> document.getElementById("id9").innerHTML = d.getMilliseconds(); <!-- 0 .. 999 --> </script> </body> </html>

Save and run it

Page 36: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

36

12 Compare &&, ||, !=

Create section12.html with these codes

<!DOCTYPE html> <html> <body> <p>Assign 5 to x, and display the value of the comparison (x == 5):</p> <p>Also assign 5 to x, and display the value of the comparison (x === "5").</p> <p id="id1"></p> <p id="id2"></p> <p id="id3"></p> <p id="id4"></p> <p id="id5"></p>

Page 37: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

37

<p id="id6"></p> <script> function myFunction() { var x = 5; var y = 6; <!-- compare equal to --> document.getElementById("id1").innerHTML = (x == 5); <!-- compare equal value and equal type --> document.getElementById("id2").innerHTML = (y === "6"); <!-- compare equal value and equal type --> document.getElementById("id3").innerHTML = (y === 6); document.getElementById("id4").innerHTML = (x > 4 && y < 4) + "<br>" + (x > 4 && y > 5) + "<br>"; document.getElementById("id5").innerHTML = (x === 4 || y === 4) + "<br>" + (x === 5 || y === 6) + "<br>"; document.getElementById("id6").innerHTML = (x != 5) + "<br>" + (y != 5) + "<br>"; } </script> <button onclick="myFunction()">Try it</button> </body> </html>

Save and run it

Page 38: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

38

Page 39: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

39

13 If-else if-else

Create section13.html with these codes

<!DOCTYPE html> <html> <body> <p id="id1"></p> <script> function myFunction() { var i =5; var j = 11; var ans = ""; if (i < 10 && j < 10) { ans = "Yes, both are < 10"; }

Page 40: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

40

else if (i > 10 || j > 10) { ans = "Yes, either i < 10 or j > 10"; } else { ans = "Don't know!"; } return ans; } document.getElementById("id1").innerHTML = myFunction(); </script> </body> </html>

Save and run it

Page 41: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

41

14 Switch case

Create section14.html with these codes

<!DOCTYPE html> <html> <body> <p id="id1"></p> <script> function myFunction() { var number =10; var ans =""; switch (number) { case 1: ans = "Number is 1"; break; case 5: ans = "Number is 5"; break; case 10: ans = "Number is 10"; break; default: ans = "Unknow number"; break; } return ans; } document.getElementById("id1").innerHTML = myFunction(); </script> </body> </html>

Save and run it

Page 42: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

42

15 For,while,do while loop Create section15.html with these codes

<!DOCTYPE html> <html> <body> <p id="id1"></p> <p id="id2"></p> <p id="id3"></p> <p id="id4"></p> <script> <!-- standard for loop --> function myForLoopStd() { <!-- standard for loop for array -->

Page 43: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

43

var arrayInt = [3,4,5]; var text =""; var len = arrayInt.length; var i; for (i = 0; i < len; i++) { text += arrayInt[i] + "<br>"; } return text; } <!-- For in loop --> function myForInLoop() { <!-- For in loop for object --> var mickeyInfo = { firstName : "Mickey", age : 50 }; var text =""; var item; for (item in mickeyInfo) { text += mickeyInfo[item] + "<br>"; } return text; } <!-- while loop --> function myWhileLoop() { var i = 0; var text =""; while (i < 5) { text += i + "<br>"; i++; } return text; } <!-- do while loop --> function myDoWhileLoop() { var i = 5; var text =""; do { text += i + "<br>"; --i; } while (i > 0) return text;

Page 44: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

44

} document.getElementById("id1").innerHTML = myForLoopStd(); document.getElementById("id2").innerHTML = myForInLoop(); document.getElementById("id3").innerHTML = myWhileLoop(); document.getElementById("id4").innerHTML = myDoWhileLoop(); </script> </body> </html>

Save and run it

16 Break, continue

Page 45: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

45

Note: “break “ keyword is break out the loop , “<br>” is a new line only, not break out the loop

Create section16.html with these codes

<!DOCTYPE html> <html> <body> <p id="id1"></p> <p id="id2"></p> <script> <!-- For in loop --> function myWhileLoop() { var i = 0; var text =""; while (i < 5) { text += i + "<br>"; if (i ==3) { break; } i++; } return text; } <!-- for loop --> function myForLoop() { var text =""; var i; for (i = 0; i < 5; i++) { if (i === 3) { continue; } text += "The number is " + i + "<br>"; } return text; } document.getElementById("id1").innerHTML = myWhileLoop(); document.getElementById("id2").innerHTML = myForLoop(); </script>

Page 46: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

46

</body> </html>

Save and run it

17 RegExpression Regular expression

Create section17.html with these codes

<!DOCTYPE html> <html> <body>

Page 47: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

47

<p>Search a string for "w3Schools", and display the position of the match:</p> <p>Replace "W3Schools" with "Microsoft" in the paragraph below:</p> <p id="id1"></p> <p id="id2"></p> <script> function mySearchFunction() { var str = "Visit W3Schools!"; var index = str.search(/w3Schools/i); <!-- ignore case --> return index; } function myRepalceFunction() { var str = "Visit W3Schools!"; var newStr = str.replace(/w3Schools/i, "Microsoft"); <!-- ignore case --> return newStr; } document.getElementById("id1").innerHTML = mySearchFunction(); document.getElementById("id2").innerHTML = myRepalceFunction(); </script> </body> </html> Save and run it

Page 48: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

48

18 Error handling try-throw-catch, text box input

Create section18.html with these codes

<!DOCTYPE html> <html> <body> <p>Please input a number between 5 and 10:</p> <p id="message"></p> <script> function myFunction() { var message, x;

Page 49: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

49

message = document.getElementById("message"); message.innerHTML = ""; x = document.getElementById("id1").value; try { x = Number(x); if(x == "") throw "is empty"; if(isNaN(x)) throw "is not a number"; if(x > 10) throw "is too high"; if(x < 5) throw "is too low"; if (x >=5 && x <=10) throw "is in range"; } catch(err) { message.innerHTML = "Input " + err; } finally { document.getElementById("id1").value = ""; } } </script> <input id="id1" type="text"> <!-- Text box --> <button type="button" onclick="myFunction()">Test Input</button> </body> </html>

Save and run it

Page 50: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

50

Page 51: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

51

19 JSON to javascript First, convert JSON into text (String) format, use the JavaScript built-in function JSON.parse() to

convert the string into a JavaScript object.

Create section19.html with these codes

<!DOCTYPE html> <html> <body> <h2>Create Object from JSON String</h2> <p id="id1"></p> <script> /*Note: reminder of JSON and XML format look like

Page 52: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

52

{ "students" : [ { "firstName":"Mickey" , "lastName":"Nguyen" ,"age":50,"weight":199.99}, { "firstName":"Patrick" , "lastName":"Nguyen","age":4 ,"weight":39.99}, { "firstName":"Sarah" , "lastName":"Nguyen","age":8 ,"weight":99.99} ] } <?xml version="1.0" encoding="UTF-8"?> <students> <student> <age>50</age> <firstName>Mickey</firstName> <lastName>Nguyen</lastName> <weight>199.99</weight> </student> <student> <age>4</age> <firstName>Patrick</firstName> <lastName>Nguyen</lastName> <weight>39.99</weight> </student> <student> <age>8</age> <firstName>Sarah</firstName> <lastName>Nguyen</lastName> <weight>99.99</weight> </student> </students> */ <!-- put JSON into text string format --> var jsonText = '{ "students" : [' + '{ "firstName":"Mickey" , "lastName":"Nguyen" ,"age":50,"weight":199.99},' + '{ "firstName":"Patrick" , "lastName":"Nguyen","age":4 ,"weight":39.99},' + '{ "firstName":"Sarah" , "lastName":"Nguyen","age":8 ,"weight":99.99} ]}'; <!-- use built-in function to convert JSON in text format into javascript object --> var studentObject = JSON.parse(jsonText); function myFunction() { var text =""; var len = studentObject.students.length; for (i = 0; i < len; i++ ) { text += studentObject.students[i].firstName + " " + studentObject.students[i].lastName + " " + studentObject.students[i].age + "<br>"; } return text; }

Page 53: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

53

document.getElementById("id1").innerHTML = myFunction(); </script> </body> </html>

Use IE web browser to open it

Use this url file:///C:/JavaTutorial/MKJavaTutorial/com.mickey.webproject/WebContent/section19.html

20 JSON Here is a quick review about JSON (JavaScript Object Notation).

Page 54: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

54

20.1 Quick review about XML

For example of Nguyen family members XML look like

<members> <member name="Mickey Nguyen"> <profession>SW Engineer</profession> <age>50</age> <gender>male</gender> </member> <member name="Chau Nguyen"> <profession>SQA Engineer</profession> <age>20</age> <gender>female</gender> </member> <member name="Patrick Nguyen"> <profession>nhoc con</profession> <age>4</age> <gender>male</gender> </member> <member name="Sarah Nguyen"> <profession>student</profession> <age>8</age> <gender>female</gender> </member> </members>

Now, with that XML above, my JSON should look like

{"members":[ { "name": "Mickey Nguyen","profession": "SW Engineer","age": "50","gender": "male" }, { "name": "Chau Nguyen","profession": "SQA Engineer","age": "20","gender": "female" }, { "name": "Patrick Nguyen","profession": "nhoc conr","age": "4","gender": "male" }, { "name": "Sarah Nguyen","profession": "student","age": "8","gender": "female" } ]}

20.2 Example of JSON JSON is javascript object, you can treat it as javascript array of object

Create section20_2.html with these codes

<!DOCTYPE html> <html> <body>

Page 55: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

55

<p>How to create a JavaScript object array.</p> <p id="id1"></p> <script> <!-- array object --> var employees = [ { "firstName":"Mickey", "lastName":"Nguyen" }, { "firstName":"Chau", "lastName":"Nguyen" }, { "firstName":"Patrick", "lastName":"Nguyen" } ]; function myFunction() { var text =""; var len = employees.length; for (i =0; i < len; i++) { text += employees[i].firstName + " " + employees[i].lastName + "<br>"; } return text; } document.getElementById("id1").innerHTML = myFunction(); </script> </body> </html>

Save and run it

Page 56: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

56

20.3 Example of Convert JSON to Javascript object. First, put JSON code syntax into text (string), thenuse JSON.parse API to convert to Javascript object

Create section20_3.html with these codes

<!DOCTYPE html> <html> <body> <h2>Create Object from JSON String</h2> <p id="id1"></p> <script> /*Note: reminder of JSON and XML format look like <members> <member name="Mickey Nguyen"> <profession>SW Engineer</profession> <age>50</age> <gender>male</gender> </member>

Page 57: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

57

<member name="Chau Nguyen"> <profession>SQA Engineer</profession> <age>20</age> <gender>female</gender> </member> <member name="Patrick Nguyen"> <profession>nhoc con</profession> <age>4</age> <gender>male</gender> </member> <member name="Sarah Nguyen"> <profession>student</profession> <age>8</age> <gender>female</gender> </member> </members> {"members":[ { "name": "Mickey Nguyen","profession": "SW Engineer","age": "50","gender": "male" }, { "name": "Chau Nguyen","profession": "SQA Engineer","age": "20","gender": "female" }, { "name": "Patrick Nguyen","profession": "nhoc con","age": "4","gender": "male" }, { "name": "Sarah Nguyen","profession": "student","age": "8","gender": "female" } ]} */ <!-- put JSON into text string format --> var jsonText = '{"members":[' + '{ "name": "Mickey Nguyen","profession": "SW Engineer","age": "50","gender": "male" },'+ '{ "name": "Chau Nguyen","profession": "SQA Engineer","age": "20","gender": "female" },'+ '{ "name": "Patrick Nguyen","profession": "nhoc con","age": "4","gender": "male" },'+ '{ "name": "Sarah Nguyen","profession": "student","age": "8","gender": "female" }]}'; <!-- use built-in function to convert JSON in text format into javascript object --> var obj = JSON.parse(jsonText); function myFunction() { var text =""; var len = obj.members.length; for (i = 0; i < len; i++ ) {

Page 58: JavaScript Tutorial Mickey Nguyen - …h2>I am using h2, this font should smaller compare to h1 This is a paragraph, whatever you want to see ... JavaScript

JavaScript Tutorial Mickey Nguyen

58

text += obj.members[i].name + " " + obj.members[i].profession + " " + obj.members[i].age + "<br>"; } return text; } document.getElementById("id1").innerHTML = myFunction(); </script> </body> </html>

Using IE web brower to open it

Use this url

file:///C:/JavaTutorial/MKJavaTutorial/com.mickey.webproject/WebContent/section20_3.html