You are on page 1of 78

JavaScript

Gio trnh JavaScript ***


chng 1 Li ni u ................................................................................................................... 4 Chng 2 Nhp mn JavaScript ................................................................................................... 5 2.1.Nhng JavaScript vo file HTML ................................................................................... 5 2.3. Th <NOScript> v </NOSCRIPT> .............................................................................. 6 2.3. Hin th mt dng text .................................................................................................. 7 2.4. Giao tip vi ngi s dng ........................................................................................ 9 2.5. im li cc lnh v m rng ..................................................................................... 11 Chng 3 Bin trong JavaScript ................................................................................................. 13 3.1. Bin v phn loI bin ............................................................................................... 13 3.2. Biu din t t trong JavaScript ................................................................................. 13 3.3. Kiu d liu ............................................................................................................... 13 1.1.1. KIu nguyn (Interger)....................................................................................... 14 1.1.2. Kiu du phy ng (Floating Point) .................................................................. 14 1.1.3. Kiu logic (Boolean) .......................................................................................... 15 1.1.4. Kiu chui (String) ............................................................................................. 15 2. Xy dng cc biu thc trong JavaScript .................................................................. 16 nh ngha v phn loI biu thc ............................................................................................... 16 Cc ton t (operator) ................................................................................................................ 16 2.1.1. Gn ................................................................................................................... 16 2.1.2. So snh............................................................................................................. 16 2.1.3. S hc............................................................................................................... 17 2.1.4. Chui .................................................................................................................. 1 2.1.5. Logic ................................................................................................................. 17 2.1.6. Bitwise .............................................................................................................. 18 Bi tp 18 2.1.7. Cu hi ............................................................................................................. 18 2.1.8. Tr li ............................................................................................................... 19 3. Cc lnh ....................................................................................................................... 20 Cu lnh iu kin...................................................................................................................... 20 Cu lnh lp ............................................................................................................................... 20 3.1.1. Vng lp for ....................................................................................................... 21 3.1.2. while ................................................................................................................. 22 3.1.3. Break ................................................................................................................ 22 3.1.4. continue ............................................................................................................ 23 Cc cu lnh thao tc trn i tng .......................................................................................... 23 3.1.5. for...in ................................................................................................................ 23 3.1.6. new ................................................................................................................... 24 3.1.7. this .................................................................................................................... 26 3.1.8. with ................................................................................................................... 26 Cc hm (Functions) .................................................................................................................. 27 Cc hm c sn ........................................................................................................................... 1 3.1.9. eval ................................................................................................................... 29

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

3.1.10. parseInt ............................................................................................................. 30 3.1.11. parseFloat ......................................................................................................... 31 Mng (Array) .............................................................................................................................. 32 S kin 33 Bi tp 37 3.1.12. Cu hi ............................................................................................................. 37 3.1.13. Tr li ............................................................................................................... 38 4. Cc i tng trong JavaScript.................................................................................. 41 i tng navigator .................................................................................................................... 43 i tng window ...................................................................................................................... 44 4.1.1. Cc thuc tnh ................................................................................................... 44 4.1.2. Cc phng thc .............................................................................................. 44 4.1.3. Cc chng trnh x l s kin ......................................................................... 46 i tng location ...................................................................................................................... 46 i tng frame ......................................................................................................................... 47 4.1.4. Cc thuc tnh ................................................................................................... 47 4.1.5. Cc phng thc .............................................................................................. 47 4.1.6. S dng Frame ................................................................................................. 47 i tng document ................................................................................................................... 49 4.1.7. Cc thuc tnh ................................................................................................... 50 4.1.8. Cc phng thc .............................................................................................. 50 i tng anchors...................................................................................................................... 50 i tng forms ......................................................................................................................... 50 4.1.9. Cc thuc tnh ................................................................................................... 51 4.1.10. Cc phng thc .............................................................................................. 51 4.1.11. Cc chng trnh x l s kin ......................................................................... 51 i tng history ........................................................................................................................ 51 4.1.12. Cc thuc tnh ................................................................................................... 51 4.1.13. Cc phng thc .............................................................................................. 51 i tng links ........................................................................................................................... 52 4.1.14. Cc thuc tnh ................................................................................................... 52 4.1.15. Cc chng trnh x l s kin ......................................................................... 52 i tng Math .......................................................................................................................... 52 4.1.16. Cc thuc tnh ................................................................................................... 52 4.1.17. Cc phng thc .............................................................................................. 53 i tng Date........................................................................................................................... 53 4.1.18. Cc phng thc .............................................................................................. 53 i tng String ......................................................................................................................... 54 4.1.19. Cc phng thc .............................................................................................. 54 Cc phn t ca i tng Form ................................................................................................ 55 4.1.20. Thuc tnh type ................................................................................................. 56 4.1.21. Phn t button .................................................................................................. 56 4.1.22. Phn t checkbox ............................................................................................. 57 4.1.23. Phn t File Upload .......................................................................................... 59 4.1.24. Phn t hidden.................................................................................................. 59 4.1.25. Phn t Password ............................................................................................. 59 4.1.26. Phn t radio .................................................................................................... 59 4.1.27. Phn t reset .................................................................................................... 61 Khoa Toan tin, i hc Quc gia H Ni

JavaScript 4.1.28. 5.

3 Phn t select ................................................................................................... 62

M hnh i tng (Object Model) .............................................................................. 71

i tng v thuc tnh .............................................................................................................. 71 To cc i tng mi................................................................................................................ 71 5.1.1. S dng khi to i tng............................................................................... 72 5.1.2. S dng mt hm xy dng(Constructor Function)............................................ 73 5.1.3. Lp mc lc cho cc thuc tnh ca i tng ................................................... 74 5.1.4. nh ngha thm cc thuc tnh cho mt kiu i tng..................................... 74 5.1.5. nh ngha cc cch thc .................................................................................. 74 5.1.6. S dng cho cc tham chiu i tng (Object References) ............................. 75 5.1.7. Xo i tng ................................................................................................... 76 6. 7. Bng tng kt cc t kho .......................................................................................... 77 Tng kt ....................................................................................................................... 78

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

chng 1 Li ni u
Vi HTML and Microsoft FrontPage bn bit cch to ra trang Web - tuy nhin ch mi mc biu din thng tin ch cha phi l cc trang Web ng c kh nng p ng cc s kin t pha ngi dng. Hng Netscape a ra ngn ng script c tn l LiveScript thc hin chc nng ny. Sau ngn ng ny c i tn thnh JavaScript tn dng tnh i chng ca ngn ng lp trnh Java. Mc d c nhng im tng ng gia Java v JavaScript, nhng chng vn l hai ngn ng ring bit. JavaScript l ngn ng di dng script c th gn vi cc file HTML. N khng c bin dch m c trnh duyt din dch. Khng ging Java phi chuyn thnh cc m d bin dch, trnh duyt c JavaScript di dng m ngun. Chnh v vy bn c th d dng hc JavaScript qua v d bi v bn c th thy cch s dng JavaScript trn cc trang Web. JavaScript l ngn ng da trn i tng, c ngha l bao gm nhiu kiu i tng, v d i tng Math vi tt c cc chc nng ton hc. Tuy vy JavaScript khng l ngn ng hng i tng nh C++ hay Java do khng h tr cc lp hay tnh tha k. JavaScript c th p ng cc s kin nh ti hay loi b cc form. Kh nng ny cho php JavaScript tr thnh mt ngn ng script ng. Ging vi HTML v Java, JavaScript c thit k c lp vi h iu hnh. N c th chy trn bt k h iu hnh no c trnh duyt h tr JavaScript. Ngoi ra JavaScript ging Java kha cnh an ninh: JavaScript khng th c v vit vo file ca ngi dng. Cc trnh duyt web nh Nescape Navigator 2.0 tr i c th hin th nhng cu lnh JavaScript c nhng vo trang HTML. Khi trnh duyt yu cu mt trang, server s gi y ni dung ca trang , bao gm c HTML v cc cu lnh JavaScript qua mng ti client. Client s c trang t u n cui, hin th cc kt qu ca HTML v x l cc cu lnh JavaScript khi no chng xut hin. Cc cu lnh JavaScript c nhng trong mt trang HTML c th tr li cho cc s kin ca ngi s dng nh kch chut, nhp vo mt form v iu hng trang. V d bn c th kim tra cc gi tr thng tin m ngi s dng a vo m khng cn n bt c mt qu trnh truyn trn mng no. Trang HTML vi JavaScript c nhng s kim tra cc gi tr c a vo v s thng bo vi ngi s dng khi gi tr a vo l khng hp l. Mc ch ca phn ny l gii thiu v ngn ng lp trnh JavaScript bn c th vit cc script vo file HTML ca mnh.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

Chng 2 Nhp mn JavaScript


2.1.Nhng JavaScript vo file HTML Bn c th nhng JavaScript vo mt file HTML theo mt trong cc cch sau y: S dng cc cu lnh v cc hm trong cp th <SCRIPT> S dng cc file ngun JavaScript S dng mt biu thc JavaScript lm gi tr ca mt thuc tnh HTML S dng th s kin (event handlers) trong mt th HTML no Trong , s dng cp th < SCRIPT >...</SCRIPT > v nhng mt file ngun JavaScript l c s dng nhiu hn c. 2.1.1.S dng th SCRIPT Script c a vo file HTML bng cch s dng cp th <SCRIPT > v <\SCRIPT >. Cc th <SCRIPT> c th xut hin trong phn <HEAD> hay <BODY> ca file HTML. Nu t trong phn <HEAD>, n s c ti v sn sng trc khi phn cn li ca vn bn c ti. Thuc tnh duy nht c nh ngha hin thi cho th <SCRIPT > l LANGUAGE= dng xc nh ngn ng script c s dng. C hai gi tr c nh ngha l "JavaScript" v "VBScript". Vi chng trnh vit bng JavaScript bn s dng c php sau :
<SCRIPT LANGUAGE=JavaScript> // INSERT ALL JavaScript HERE </SCRIPT > Ch : Ghi ch khng c t trong cp th <- v -> nh ghi ch trong file HTML. C php ca JavaScript tng t c php ca C nn c th s dng // hay /* ... */.

im khc nhau gia c php vit cc ghi ch gia HTML v JavaScript l cho php bn n cc m JavaScript trong cc ghi ch ca file HTML, cc trnh duyt c khng h tr cho JavaScript c th c c n nh trong v d sau y:
<SCRIPT LANGUAGE=JavaScript> <!-- From here the JavaScript code hidden // INSERT ALL JavaScript HERE // This is where the hidden ends --> </SCRIPT >

Dng cui cng ca script cn c du // trnh duyt khng din dch dng ny di dng m JavaScript. Cc v d trong chng ny khng cha c im n ca JavaScript m c th d hiu hn. 2.1.2. S dng mt file ngun JavaScript Thuc tnh SRC ca th <SCRIPT> cho php bn ch r file ngun JavaScript c s dng (dng phng php ny hay hn nhng trc tip mt on lnh JavaScript vo trang HTML).

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

C php:
<SCRIPT SRC="file_name.js"> .... </SCRIPT >

Thuc tnh ny ry hu dng cho vic chia s cc hm dng chung cho nhiu trang khc nhau. Cc cu lnh JavaScript nm trong cp th < SCRIPT> v </SCRIPT> c cha thuc tinh SRC tr khi n c li. V d bn mun a dng lnh sau vo gia cp th <SCRIPT SRC="..."> v </SCRIPT>:
document.write("Khng tm thy file JS a vo!");

Thuc tnh SRC c th c nh r bng a ch URL, cc lin kt hoc cc ng dn tuyt i, v d:


<SCRIPT SRC=" http://cse.com.vn ">

Cc file JavaScript bn ngoi khng c cha bt k Ch th HTML no. Chng ch c cha cc cu lnh Khi bn mun ch ra mt xu JavaScript v nh ngha hm. trch dn trong mt xu khc cn Tn file ca cc hm JavaScript bn ngoi cn c ui s dng du nhy n ( ' ) .js, v server s phi nh x ui .js ti kiu MIME phn nh xu . iu ny cho application/x-javascript. l nhng g m server gi php script nhn ra xu k t . tr li phn Header ca file HTML. nh x ui ny vo kiu MIME, ta thm dng sau vo file mime.types trong ng dn cu hnh ca server, sau khi ng li server:
type=application/x-javascript Nu server khng nh x c ui .js ti kiu MIME application/x-javascript , Navigator

s ti file JavaScript c ch ra trong thuc tnh SRC v khng ng cch. Trong v d sau, hm bar c cha xu "left" nm trong mt cp du nhy kp:
function bar(widthPct){ document.write(" <HR ALIGN='LEFT' WIDTH="+widthPct+"%>") }

2.3. Th <NOScript> v </NOSCRIPT> Cp th ny dng nh r ni dung thng bo cho ngi s dng bit trnh duyt khng h tr JavaScript. Khi trnh duyt s khng hiu th <NOSCRIPT> v n b l i, cn on m nm trong cp th ny s c Navigator hin th. Ngc li, nu trnh duyt c h tr JavaScript th on m trong cp th <NOSCRIPT> s c b qua. Tuy nhin, iu ny cng c th xy ra nu ngi s dng khng s dng JavaScript trong trnh duyt ca mnh bng cch tt n i trong hp Preferences/Advanced. V d:
<NOSCRIPT > <B> Trang ny c s dng JavaScript. Do bn cn s dng trnh duyt Netscape Navigator t version 2.0 tr i! <BR> <A HREF="http://home.netscape.com/comprd/mirror/index.html"> Hy kch chut vo y ti v phin bn Netscape mi hn

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

</A> </BR> Nu bn s dng trnh duyt Netscape t 2.0 tr i m vn c c dng ch ny th hy bt Preferences/Advanced/JavaScript ln </NOSCRIPT>

Hnh 2.3: Minh ho th NOSCRIPT 2.3. Hin th mt dng text Trong hu ht cc ngn ng lp trnh, mt trong nhng kh nng c s l hin th ra mn hnh mt dng text. Trong JavaScript, ngi lp trnh cng c th iu khin vic xut ra mn hnh ca client mt dng text tun t trong file HTML. JavaScript s xc nh im m n s xut ra trong file HTML v dng text kt qu s c dch nh cc dng HTML khc v hin th trn trang. Hn na, JavaScript cn cho php ngi lp trnh sinh ra mt hp thng bo hoc xc nhn gm mt hoc hai nt. Ngoi ra, dng text v cc con s cn c th hin th trong trng TEXT v TEXTAREA ca mt form. Trong phn ny, ta s hc cch thc write() v writeln() ca i tng document. i tng document trong JavaScript c thit k sn hai cch thc xut mt dng text ra mn hnh client: write() v writeln(). Cch gi mt cch thc ca mt i tng nh sau:
object_name.property_name

D liu m cch thc dng thc hin cng vic ca n c a vo dng tham s, v d:
document.write("Test"); document.writeln('Test');

Khoa Toan tin, i hc Quc gia H Ni

JavaScript Cch thc write() xut ra mn hnh xu Text nhng khng xung dng, cn cch thc writeln() sau khi vit xong dng Text t ng xung dng. Hai cch thc ny u cho php xut ra th HTML.

V d: Cch thc write() xut ra th HTML


<HTML> <HEAD> <TITLE>Ouputting Text</TITLE> </HEAD> <BODY> This text is plain.<BR> <B> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM OTHER BROWSERS document.write("This text is bold.</B>"); // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </BODY> </HTML>

V d: S khc nhau ca write() v writeln():


<PRE> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM OTHER BROWSERS document.writeln("One,"); document.writeln("Two,"); document.write("Three "); document.write("..."); // STOP HIDING FROM OTHER BROWSERS -->

Khoa Toan tin, i hc Quc gia H Ni

JavaScript </SCRIPT> </PRE>

Khi duyt s c kt qu:

Hnh 2.5: S khc nhau ca write() v writeln() 2.4. Giao tip vi ngi s dng JavaScript h tr kh nng cho php ngi lp trnh to ra mt hp hi thoi. Ni dung ca hp hi thoi ph thuc vo trang HTML c cha on script m khng lm nh hng n vic xut ni dung trang. Cch n gin lm vic l s dng cch thc alert(). s dng c cch thc ny, bn phi a vo mt dng text nh khi s dng document.write() v document.writeln() trong phn trc. V d: alert("Nhn vo OK tip tc"); Khi file s ch cho n khi ngi s dng nhn vo nt OK ri mi tip tc thc hin Thng thng, cch thc alert() c s dng trong cc trng hp: Thng tin a v form khng hp l Kt qu sau khi tnh ton khng hp l Khi dch v cha sn sng truy nhp d liu Tuy nhin cch thc alert() mi ch cho php thng bo vi ngi s dng ch cha thc s giao tip vi ngi s dng. JavaScript cung cp mt cch thc khc giao tip vi ngi s dng l promt(). Tng t nh alert(), prompt() to ra mt hp hi thoi vi mt dng thng bo do bn a vo, nhng ngoi ra n cn cung cp mt trng nhp d

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

10

liu vo. Ngi s dng c th nhp vo trng ri kch vo OK. Khi , ta c th x l d liu do ngi s dng va a vo. V d: Hp hi thoi gm mt dng thng bo, mt trng nhp d liu, mt nt OK v mt nt Cancel Chng trnh ny s hi tn ngi dng v sau s hin th mt thng bo ngn s dng tn mi a vo. V d c lu vo file Hello.html
<HTML> <HEAD> <TITLE> JavaScript Exemple </TITLE> <SCRIPT LANGUAGE= JavaScript> var name=window.prompt(Hello! Whats your name ?,); document.write(Hello + name + ! I hope you like JavaScript ); </SCRIPT> </HEAD> <BODY> </BODY> </HTML>

Khi duyt c kt qu:

Hnh2.1: Hin th ca s nhp tn V d ny hin th du nhc nhp vo tn vi phng thc window.prompt. Gi tr t c s c ghi trong bin c tn l name. Bin name c kt hp vi cc chui khc v c hin th trong ca s ca trnh duyt nh phng thc document.write.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

11

Hnh 2.2: Hin th li cho ngi nhp By gi bn c tng v cc chc nng c th t c qua JavaScript, chng ta hy tip tc tm hiu thm v chnh ngn ng ny. 2.5. im li cc lnh v m rng
Lnh/M rng SCRIPT SRC Kiu th HTML Thuc tnh ca th SCRIPT thuc tnh ca th SCRIPT Ghi ch trong JavaScript Ghi ch trong JavaScript cch thc JavaScript Cch thc JavaScript Cch thc ca JavaScript M t Hp cha cc lnh JavaScript Gi a ch ca file JavaScript bn ngoi. File ny phi c phn ui .js nh r ngn ng script c s dng (JavaScript hoc VBScript) nh du ghi ch mt dng trong on script nh du ghi ch mt khi trong on script Xut ra mt xu trn ca s hin thi mt cch tun t theo file HTML c on script Tng t cch thc document.write() nhng vit xong t xung dng. Hin th mt dng thng bo trn hp hi thoi

LANGUAGE

// /*...*/ document.write() document.writeln() alert()

Khoa Toan tin, i hc Quc gia H Ni

JavaScript promt() Cch thc JavaScript Hin th mt dng thng bo trong hp hi thoi ng thi cung cp mt trng nhp d liu ngi s dng nhp vo.

12

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

13

Chng 3 Bin trong JavaScript


3.1. Bin v phn loI bin Tn bin trong JavaScript phi bt u bng ch hay du gch di. Cc ch s khng c s dng m u tn mt bin nhng c th s dng sau k t u tin. Phm vi ca bin c th l mt trong hai kiu sau: Bin ton cc: C th c truy cp t bt k u trong ng dng. c khai bo nh sau :

x = 0;
Bin cc b: Ch c truy cp trong phm vi chng trnh m n khai bo. Bin cc b c khai bo trong mt hm vi t kho var nh sau:

var x = 0;
Bin ton cc c th s dng t kho var, tuy nhin iu ny khng thc s cn thit. 3.2. Biu din t t trong JavaScript T t l cc gi tr trong chng trnh khng thay i. Sau y l cc v d v t t:
8 The dog ate my shoe true
Ch Khc vi C, trong JavaScript khng c kiu hng s CONST biu din mt gi tr khng i no y

3.3. Kiu d liu Khc vi C++ hay Java, JavaScript l ngn ng c tnh nh kiu thp. iu ny c ngha l khng phi ch ra kiu d liu khi khai bo bin. Kiu d liu c t ng chuyn thnh kiu ph hp khi cn thit. V d file Variable.Html:
<HTML> <HEAD> <TITLE> Datatype Example </TITLE> <SCRIPT LANGUAGE= "JavaScript"> var fruit='apples'; var numfruit=12; numfruit = numfruit + 20; var temp ="There are " + numfruit + " " + "."; document.write(temp); </SCRIPT> </HEAD> <BODY> </BODY>

</HTML> Cc trnh duyt h tr JavaScript s x l chnh xc v d trn v a ra kt qu di y:

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

14

Trnh din dch JavaScript s xem bin numfruit c kiu nguyn khi cng vi 20 v c kiu chui khi kt hp vi bin temp. Trong JavaScript, c b n kiu d liu sau y: kiu s nguyn, kiu du phy ng, kiu logic v kiu chui. 1.1.1. KIu nguyn (Interger) S nguyn c th c biu din theo ba cch: H c s 10 (h thp phn) - c th biu din s nguyn theo c s 10, ch rng ch s u tin phi khc 0. H c s 8 (h bt phn) - s nguyn c th biu din di dng bt phn vi ch s u tin l s 0. H c s 16 (h thp lc phn) - s nguyn c th biu din di dng thp lc phn vi hai ch s u tin l 0x. 1.1.2. Kiu du phy ng (Floating Point) Mt literal c kiu du phy ng c 4 thnh phn sau: Phn nguyn thp phn. Du chm thp phn (.). Hnh 3.1: Kt qu ca x l d liu Phn d. Phn m. phn bit kiu du phy ng vi kiu s nguyn, phi c t nht mt ch s theo sau du chm hay E. V d:
9.87 -0.85E4 9.87E14
Khoa Toan tin, i hc Quc gia H Ni

JavaScript

15

.98E-3

1.1.3. Kiu logic (Boolean) Kiu logic c s dng ch hai iu kin : ng hoc sai. Min gi tr ca kiu ny ch c hai gi tr true. false. 1.1.4. Kiu chui (String) Mt literal kiu chui c biu din bi khng hay nhiu k t c t trong cp du " ... " hay '... '. V d:
The dog ran up the tree The dog barked 100

biu din du nhy kp ( " ), trong chui s dng ( \" ), v d:


document.write( \This text inside quotes.\ );

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

16

2.

Xy dng cc biu thc trong JavaScript


nh ngha v phn loI biu thc

Tp hp cc literal, bin v cc ton t nhm nh gi mt gi tr no c gi l mt biu thc (expression). V c bn c ba kiu biu thc trong JavaScript: S hc: Nhm lng gi gi tr s. V d (3+4)+(84.5/3) c nh gi bng 197.1666666667. Chui: Nhm nh gi chui. V d "The dog barked" + barktone + "!" l The dog barked ferociously!. Logic: Nhm nh gi gi tr logic. V d temp>32 c th nhn gi tr sai. JavaScript cng h tr biu thc iu kin, c php nh sau:
(condition) ? valTrue : valFalse

Nu iu kin condition c nh gi l ng, biu thc nhn gi tr valTrue, ngc li nhn gi tr valFalse. V d:
state = (temp>32) ? "liquid" : "solid"

Trong v d ny bin state c gn gi tr "liquid" nu gi tr ca bin temp ln hn 32; trong trng hp ngc li n nhn gi tr "solid".

Cc ton t (operator)
Ton t c s dng thc hin mt php ton no trn d liu. Mt ton t c th tr li mt gi tr kiu s, kiu chui hay kiu logic. Cc ton t trong JavaScript c th c nhm thnh cc loi sau y: gn, so snh, s hc, chui, logic v logic bitwise. 2.1.1. Gn Ton t gn l du bng (=) nhm thc hin vic gn gi tr ca ton hng bn phi cho ton hng bn tri. Bn cnh JavaScript cn h tr mt s kiu ton t gn rt gn. Kiu gn thng thng x=x+y x=x-y x=x*y x=x/y x=x%y 2.1.2. So snh Ngi ta s dng ton t so snh so snh hai ton hng v tr li gi tr ng hay sai ph thuc vo kt qu so snh. Sau y l mt s ton t so snh trong JavaScript: == != Tr li gi tr ng nu ton hng bn tri bng ton hng bn phi Tr li gi tr ng nu ton hng bn tri khc ton hng bn phi Kiu gn rt gn x+=y x-= y x*=y x/=y x%=y

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

17

> >= < <=

Tr li gi tr ng nu ton hng bn tri ln hn ton hng bn phi Tr li gi tr ng nu ton hng bn tri ln hn hoc bng ton hng bn phi Tr li gi tr ng nu ton hng bn tri nh hn ton hng bn phi Tr li gi tr ng nu ton hng bn tri nh hn hoc bng ton hng bn phi

2.1.3. S hc Bn cnh cc ton t cng (+), tr ( -), nhn (*), chia (/) thng thng, JavaScript cn h tr cc ton t sau y: var1% var2 var++ var-Ton t phn d, tr li phn d khi chia var1 cho var2 Ton t ph nh, c gi tr ph nh ton hng Ton t ny tng var ln 1 (c th biu din l ++var) Ton t ny gim var i 1 (c th biu din l --var)

Ch
Nu bn gn gi tr ca ton t ++ hay -- vo mt bin, nh y= x++, c th c cc kt qu khc nhau ph thuc vo v tr xut hin trc hay sau ca ++ hay -- vi tn bin (l x trong trng hp ny). Nu ++ ng trc x, x s c tng hoc gim trc khi gi tr x c gn cho y. Nu ++ hay -- ng sau x, gi tr ca x c gn cho y trc khi n c tng hay gim.

2.1.4. Chui Khi c s dng vi chui, ton t + c coi l kt hp hai chui, v d: "abc" + "xyz" c "abcxyz" 2.1.5. Logic JavaScript h tr cc ton t logic sau y:
expr1 && expr2

L ton t logic AND, tr li gi tr ng nu c expr1 v expr2 cng ng. L ton t logic OR, tr li gi tr ng nu t nht mt trong hai expr1 v expr2 ng. L ton t logic NOT ph nh gi tr ca expr.

expr1 || expr2

! expr

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

18

2.1.6. Bitwise Vi cc ton t thao tc trn bit, u tin gi tr c chuyn di dng s nguyn 32 bit, sau ln lt thc hin cc php ton trn tng bit. & Ton t bitwise AND, tr li gi tr 1 nu c hai bit cng l 1. | Ton t bitwise OR, tr li gi tr 1 nu mt trong hai bit l 1. ^ Ton t bitwise XOR, tr li gi tr 1 nu hai bit c gi tr khc nhau Ngoi ra cn c mt s ton t dch chuyn bitwise. Gi tr c chuyn thnh s nguyn 32 bit trc khi dch chuyn. Sau khi dch chuyn, gi tr li c chuyn thnh kiu ca ton hng bn tri. Sau y l cc ton t dch chuyn: << Ton t dch tri. Dch chuyn ton hng tri sang tri mt s lng bit bng ton hng phi. Cc bit b chuyn sang tri b mt v 0 thay vo pha bn phi. V d: 4<<2 tr thnh 16 (s nh phn 100 tr thnh s nh phn 10000) >> Ton t dch phi. Dch chuyn ton hng tri sang phi mt s lng bit bng ton hng phi. Cc bit b chuyn sang phi b mt v du ca ton hng bn tri c gi nguyn. V d: 16>>2 tr thnh 4 (s nh phn 10000 tr thnh s nh phn 100) >>> Ton t dch phi c chn 0. Dch chuyn ton hng tri sang phi mt s lng bit bng ton hng phi. Bit du c dch chuyn t tri (ging >>). Nhng bit c dch sang phi b xo i. V d: -8>>>2 tr thnh 1073741822 (bi cc bit du tr thnh mt phn ca s). Tt nhin vi s dng kt qu ca ton t >> v >>> l ging nhau.

C mt s ton t dch chuyn bitwise rt gn: Kiu bitwise thng thng x = x << y x = x >> y x = x >>> y x=x&y x=x^y x=x|y Kiu bitwise rt gn x << = y x - >> y x >>> = y x&=y x^=y x|=y

Bi tp
2.1.7. Cu hi Hy nh gi cc biu thc sau: 1. a. 7 + 5 b. "7" + "5" c. 7 == 7 d. 7 >= 5

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

19

e. 7 <= 7 2. f. (7 < 5) ? 7 : 5 g. (7 >= 5) && (5 > 5) h. (7 >= 5) || (5 > 5) 2.1.8. Tr li Cc biu thc c nh gi nh sau: 1. a. 12 b. "75" c. true d. true e. true 2. f. 5 g. false h. true

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

20

3.

Cc lnh

C th chia cc lnh ca JavaScript thnh ba nhm sau: Lnh iu kin. Lnh lp. Lnh tho tc trn i tng.

Cu lnh iu kin
Cu lnh iu kin cho php chng trnh ra quyt nh v thc hin cng vic no y da trn kt qu ca quyt nh. Trong JavaScript, cu lnh iu kin l if...else

if ... else
Cu lnh ny cho php bn kim tra iu kin v thc hin mt nhm lnh no y da trn kt qu ca iu kin va kim tra. Nhm lnh sau else khng bt buc phi c, n cho php ch ra nhm lnh phi thc hin nu iu kin l sai. C php
if ( <iu kin> ) { //Cc cu lnh vi iu kin ng } else { //Cc cu lnh vi iu kin sai }

V d:
if (x==10){ document.write(x bng 10, t li x bng 0.); x = 0; } else document.write(x khng bng 10.);

Ch
K t { v } c s dng tch cc khi m.

Cu lnh lp
Cu lnh lp th hin vic lp i lp li mt on m cho n khi biu thc iu kin c nh gi l ng. JavaScipt cung cp hai kiu cu lnh lp: for loop while loop

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

21

3.1.1. Vng lp for Vng lp for thit lp mt biu thc khi u - initExpr, sau lp mt on m cho n khi biu thc <iu kin> c nh gi l ng. Sau khi kt thc mi vng lp, biu thc incrExpr c nh gi li. C php: for (initExpr; <iu kin> ; incrExpr){ //Cc lnh c thc hin trong khi lp } V d:
<HTML> <HEAD> <TITLE>For loop Example </TITLE> <SCRIPT LANGUAGE= "JavaScript"> for (x=1; x<=10 ; x++) { y=x*25; document.write("x ="+ x +";y= "+ y + "<BR>"); } </SCRIPT> </HEAD> <BODY></BODY> </HTML>

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

22

Hnh 5.1: Kt qu ca lnh for...loop V d ny lu vo file for_loop.Html. Vng lp ny s thc hin khi m lnh cho n khi x>10. 3.1.2. while Vng lp while lp khi lnh chng no <iu kin> cn c nh gi l ng C php: while (<iu kin>) { //Cc cu lnh thc hin trong khi lp } V d:
x=1; while (x<=10){ y=x*25; document.write("x="+x +"; y = "+ y + "<BR>"); x++; }

Kt qu ca v d ny ging nh v d trc. 3.1.3. Break Cu lnh break dng kt thc vic thc hin ca vng lp for hay while. Chng trnh c tip tc thc hin ti cu lnh ngay sau ch kt thc ca vng lp. C php
break;

on m sau lp cho n khi x ln hn hoc bng 100. Tuy nhin nu gi tr x a vo vng lp nh hn 50, vng lp s kt thc V d:
while (x<100)

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

23

{ if (x<50) break; x++; }

3.1.4. continue Lnh continue ging lnh break nhng khc ch vic lp c kt thc v bt u t u vng lp. i vi vng lp while, lnh continue iu khin quay li <iu kin>; vi for, lnh continue iu khin quay li incrExpr. C php
continue;

V d: on m sau tng x t 0 ln 5, nhy ln 8 v tip tc tng ln 10


x=0; while (x<=10) { document.write(Gi tr ca x l:+ x+<BR>); if (x=5) { x=8; continue; } x++; }

Cc cu lnh thao tc trn i tng


JavaScript l mt ngn ng da trn i tng, do n c mt s cu lnh lm vic vi cc i tng. 3.1.5. for...in Cu lnh ny c s dng lp tt c cc thuc tnh (properties) ca mt i tng. Tn bin c th l mt gi tr bt k, ch cn thit khi bn s dng cc thuc tnh trong vng lp. V d sau s minh ho iu ny C php
for (<variable> in <object>) { //Cc cu lnh }

V d V d sau s ly ra tt c cc thuc tnh ca i tng Window v in ra tn ca mi thuc tnh. Kt qu c minh ho trn hnh 5.2.
<HTML> <HEAD> <TITLE>For in Example </TITLE> <SCRIPT LANGUAGE= "JavaScript">
Khoa Toan tin, i hc Quc gia H Ni

JavaScript

24

document.write("The properties of the Window object are: <BR>"); for (var x in window) document.write(" "+ x + ", "); </SCRIPT> </HEAD> <BODY> </BODY> </HTML>

Hnh 5.2: Kt qu ca lnh for...in

3.1.6. new Bin new c thc hin to ra mt th hin mi ca mt i tng C php


objectvar = new object_type ( param1 [,param2]... [,paramN])

V d sau to i tng person c cc thuc tnh firstname, lastname, age, sex . Ch rng t kho this c s dng ch i tng trong hm person. Sau ba th hin ca i tng person c to ra bng lnh new

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

25

<HTML> <HEAD> <TITLE>New Example </TITLE> <SCRIPT LANGUAGE= "JavaScript"> function person(first_name, last_name, age, sex){ this.first_name=first_name; this.last_name=last_name; this.age=age; this.sex=sex; } person1= new person("Thuy", "Dau Bich", "23", "Female"); person2= new person("Chung", "Nguyen Bao", "24", "Male"); person3= new person("Binh", "Nguyen Nhat", "24", "Male"); person4= new person("Hon", " Vn", "24", "Male"); document.write ("1. "+person1.last_name+" " + person1.first_name + "<BR>" ); document.write("2. "+person2.last_name +" "+ person2.first_name + "<BR>"); document.write("3. "+ person3.last_name +" "+ person3.first_name + "<BR>"); document.write("4. "+ person4.last_name +" "+ person4.first_name+"<BR>"); </SCRIPT> </HEAD> <BODY> </BODY> </HTML>

Hnh 5.3: Kt qu ca v d lnh New

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

26

3.1.7. this T kho this c s dng ch i tng hin thi. i tng c gi thng l i tng hin thi trong phng thc hoc trong hm. C php
this [.property]

C th xem v d ca lnh new. 3.1.8. with Lnh ny c s dng thit lp i tng ngm nh cho mt nhm cc lnh, bn c th s dng cc thuc tnh m khng cp n i tng. C php
with (object) { // statement }

V d: V d sau ch ra cch s dng lnh with thit lp i tng ngm nh l document v c th s dng phng thc write m khng cn cp n i tng document
<HTML> <HEAD> <TITLE>With Example </TITLE> <SCRIPT LANGUAGE= "JavaScript"> with (document){ write(This is an exemple of the things that can be done <BR>); write(With the <B>with<B> statment. <P>); write(This can really save some typing); } </SCRIPT> </HEAD> <BODY> </BODY> </HTML>

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

27

Hnh 5.4: Kt qu ca v d lnh with

Cc hm (Functions)
JavaScript cg cho php s dng cc hm. Mc d khng nht thit phi c, song cc hm c th c mt hay nhiu tham s truyn vo v mt gi tr tr v. Bi v JavaScript l ngn ng c tnh nh kiu thp nn khng cn nh ngha kiu tham s v gi tr tr v ca hm. Hm c th l thuc tnh ca mt i tng, trong trng hp ny n c xem nh l phng thc ca i tng . Lnh function c s dng to ra hm trong JavaScript. C php
function fnName([param1],[param2],...,[paramN]) { //function statement }

V d: V d sau minh ho cch thc to ra v s dng hm nh l thnh vin ca mt i tng. Hm printStats c to ra l phng thc ca i tng person
<HTML> <HEAD> <TITLE>Function Example </TITLE> <SCRIPT LANGUAGE= "JavaScript"> function person(first_name, last_name, age, sex) { this.first_name=first_name; this.last_name=last_name; this.age=age;

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

28

this.sex=sex; this.printStats=printStats; } function printStats() { with (document) { write (" Name :" + this.last_name + " " + this.first_name + "<BR>" ); write("Age :"+this.age+"<BR>"); write("Sex :"+this.sex+"<BR>"); } } person1= new person("Thuy", "Dau Bich", "23", "Female"); person2= new person("Chung", "Nguyen Bao", "24", "Male"); person3= new person("Binh", "Nguyen Nhat", "24", "Male"); person4= new person("Hoan", "Do Van", "23", "Male"); person1.printStats(); person2.printStats(); person3.printStats(); person4.printStats(); </SCRIPT> </HEAD> <BODY> </BODY> </HTML>

1 1 1 1 1

Hnh 8: V d v hm

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

29

Cc hm c sn
JavaScript c mt s hm c sn, gn trc tip vo chnh ngn ng v khng nm trong mt i tng no: eval parseInt parseFloat 3.1.9. eval Hm ny c s dng nh gi cc biu thc hay lnh. Biu thc, lnh hay cc i tng ca thuc tnh u c th c nh gi. c bit ht sc hu ch khi nh gi cc biu thc do ngi dng a vo (ngc li c th nh gi trc tip). C php: returnval=eval (bt k biu thc hay lnh hp l trong Java) V d:
<HTML> <HEAD> <TITLE>Eval Example </TITLE> <SCRIPT LANGUAGE= "JavaScript"> var string=10+ Math.sqrt(64); document.write(string+ =+ eval(string)); </SCRIPT>

Hnh 5.5: Kt qu vic s dng hm


</HEAD> <BODY> </BODY> </HTML>

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

30

Hnh 5.6 V d hm Eval 3.1.10. parseInt Hm ny chuyn mt chui s thnh s nguyn vi c s l tham s th hai (tham s ny khng bt buc). Hm ny thng c s dng chuyn cc s nguyn sang c s 10 v m bo rng cc d liu c nhp di dng k t c chuyn thnh s trc khi tnh ton. Trong trng hp d liu vo khng hp l, hm parseInt s c v chuyn dng chui n v tr n tm thy k t khng phi l s. Ngoi ra hm ny cn ct du phy ng. C php
parseInt (string, [, radix])

V d:
<HTML> <HEAD> <TITLE> perseInt Exemple </TITLE> <SCRIPT LANGUAGE= "JavaScript"> document.write("Converting 0xC hex to base-10: " + parseInt(0xC,10) + "<BR>"); document.write("Converting 1100 binary to base-10: " + parseInt(1100,2) + "<BR>"); </SCRIPT> </HEAD> <BODY> </BODY>

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

31

</HTML>

Hnh 5.7: V d parInt 3.1.11. parseFloat Hm ny ging hm parseInt nhng n chuyn chui thnh s biu din di dng du phy ng. C php
parseFloat (string)

V d: V d sau minh ho cch thc x l ca parseFloat vi cc kiu chui khc nhau. Hnh 5.8 minh ha kt qu
<HTML> <HEAD> <TITLE> perseFload Exemple </TITLE> <SCRIPT LANGUAGE= "JavaScript"> document.write("This script will show how diffrent strings are "); document.write("Converted using parseFloat<BR>"); document.write("137= " + parseFloat("137") + "<BR>"); document.write("137abc= " + parseFloat("137abc") + "<BR>"); document.write("abc137= " + parseFloat("abc137") + "<BR>"); document.write("1abc37= " + parseFloat("1abc37") + "<BR>"); </SCRIPT> </HEAD> <BODY> </BODY>

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

32

</HTML>

Hnh 5.8 : Kt qu ca v d parseFloat

Mng (Array)
Mc d JavaScript khng h tr cu trc d liu mng nhng Netscape to ra phng thc cho php bn t to ra cc hm khi to mng nh sau:
function InitArray(NumElements){ this.length = numElements; for (var x=1; x<=numElements; x++){ this[x]=0 } return this; }

N to ra mt mng vi kch thc xc nh trc v in cc gi tr 0. Ch rng thnh phn u tin trong mng l di mng v khng c s dng. to ra mt mng, khai bo nh sau:
myArray = new InitArray (10)

N to ra cc thnh phn t myArray[1] n myArray[10] vi gi tr l 0. Gi tr cc thnh phn trong mng c th c thay i nh sau:
myArray[1] = "Ngh An" myArray[2] = "Lo"

Sau y l v d y :
<HTML> <HEAD> <TITLE> Array Exemple </TITLE> <SCRIPT LANGUAGE= "JavaScript"> function InitArray(numElements) { this.length = numElements; for (var x=1; x<=numElements; x++){
Khoa Toan tin, i hc Quc gia H Ni

JavaScript

33

this[x]=0 } return this; } myArray = new InitArray(10); myArray[1] = "Ngh An"; myArray[2] = "H Ni"; document.write(myArray[1] + "<BR>"); document.write(myArray[2] + "<BR>"); </SCRIPT> </HEAD> <BODY> </BODY> </HTML>

Hnh 5.9: V d mng

S kin
JavaScript l ngn ng nh hng s kin, ngha l s phn ng trc cc s kin xc nh trc nh kch chut hay ti mt vn bn. Mt s kin c th gy ra vic thc hin mt on m lnh (gi l cc chng trinh x l s kin) gip cho chng trnh c th phn ng mt cch thch hp.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

34

Chng trnh x l s kin (Event handler):


<tagName eventHandler = "JavaScript Code or Function">

Mt on m hay mt hm c thc hin phn ng trc mt s kin gi l chng trnh x l s kin. Chng trnh x l s kin c xc nh l mt thuc tnh ca mt th HTML: V d sau gi hm CheckAge() mi khi gi tr ca trng vn bn thay i:
<INPUT TYPE=TEXT NAME="AGE" onChange="CheckAge()">

on m ca chng trnh x l s kin khng l mt hm; n l cc lnh ca JavaScript cch nhau bng du chm phy. Tuy nhin cho mc ch vit thnh cc module nn vit di dng cc hm. Mt s chng trnh x l s kin trong JavaScript:
onBlur onClick

Xy ra khi input focus b xo t thnh phn form Xy ra khi ngi dng kch vo cc thnh phn hay lin kt ca form. Xy ra khi gi tr ca thnh phn c chn thay i Xy ra khi thnh phn ca form c focus(lm ni ln). Xy ra trang Web c ti. Xy ra khi di chuyn chut qua kt ni hay anchor. Xy ra khi ngi s dng la chn mt trng nhp d liu trn form. Xy ra khi ngi dng a ra mt form. Xy ra khi ngi dng ng mt trang

onChange onFocus onLoad onMouseOver onSelect

onSubmit onUnLoad

Sau y l bng cc chng trnh x l s kin c sn ca mt s i tng. Cc i tng ny s c trnh by k hn trong phn sau. i tng Selection list Text Textarea Button Checkbox Radio button Hypertext link Clickable Imagemap area Reset button Chng trnh x l s kin c sn onBlur, onChange, onFocus onBlur, onChange, onFocus, onSelect onBlur, onChange, onFocus, onSelect onClick onClick onClick onClick, onMouseOver, onMouseOut onMouseOver, onMouseOut onClick

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

35

Submit button Document Window Framesets Form Image

onClick onLoad, onUnload, onError onLoad, onUnload, onBlur, onFocus onBlur, onFocus onSubmit, onReset onLoad, onError, onAbort

V d sau l mt on m script n gin ca chng trnh x l s kin thm nh gi tr a vo trong trng text. Tui ca ngi s dng c nhp vo trong trng ny v chng trnh x l s kin s thm nh tnh hp l ca d liu a vo. Nu khng hp l s xut hin mt thng bo yu cu nhp li. Chng trnh x l s kin c gi mi khi trng AGE b thay i v focus chuyn sang trng khc. Hnh 5.10 minh ho kt qu ca v d ny
<HTML> <HEAD> <TITLE> An Event Handler Exemple </TITLE> <SCRIPT LANGUAGE= "JavaScript"> function CheckAge(form) { if ( (form.AGE.value<0)||(form.AGE.value>120) ) { alert("Tui nhp vo khng hp l! Mi bn nhp li"); form.AGE.value=0; } } </SCRIPT> </HEAD> <BODY> <FORM NAME="PHIEU_DIEU_TRA">

Nhp vo tn ca bn:<BR>
Tn <INPUT TYPE=TEXT NAME="TEN" MAXLENGTH=10 SIZE=10><BR> m <INPUT TYPE=TEXT NAME="DEM" MAXLENGTH=15 SIZE=10><BR> H <INPUT TYPE=TEXT NAME="HO" MAXLENGTH=10 SIZE=10><BR> Age <P> <INPUT TYPE=TEXT NAME="AGE" MAXLENGTH=3 onChange="CheckAge(PHIEU_DIEU_TRA)"><BR> SIZE=2

Bn thch ma no nht:<BR>
Ma xun<INPUT TYPE=RADIO NAME="MUA" VALUE="Mua xuan">
Khoa Toan tin, i hc Quc gia H Ni

JavaScript

36

Ma h<INPUT TYPE=RADIO NAME="MUA" VALUE="Mua ha"> Ma thu<INPUT TYPE=RADIO NAME="MUA" VALUE="Mua thu"> Ma ng<INPUT TYPE=RADIO NAME="MUA" VALUE="Mua dong"> <P>

Hy chn nhng hot ng ngoi tri m bn yu thch:<BR>


i b<INPUT TYPE=CHECKBOX NAME="HOAT_DONG" VALUE="Di bo"> Trt tuyt<INPUT TYPE=CHECKBOX NAME="HOAT_DONG" VALUE="Truot tuyet"> Th thao di nc<INPUT TYPE=CHECKBOX VALUE="Duoi nuoc"> NAME="HOAT_DONG"

p xe<INPUT TYPE=CHECKBOX NAME="HOAT_DONG" VALUE="Dap xe"> <P> <INPUT TYPE=SUBMIT> <INPUT TYPE=RESET> </FORM> </BODY> </HTML>

Hnh 5.10: Minh ho cho v d Event Handler

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

37

Bi tp
3.1.12. Cu hi 1. Vit mt on lnh JavaScript s dng cch thc confirm() v cu lnh if...then thc hin: Hi ngi s dng c mun nhn c mt li cho khng Nu c th hin nh wellcome.jpg v mt li cho. Nu khng th vit ra mt li thng bo 2. Vit mt on lnh JavaScript thc hin: Hi ngi s dng: "10+10 bng bao nhiu?" Nu ng th hi tip: C mun tr li cu th hai khng?" Nu mun th hi: "10*10 bng bao nhiu?" nh gi kt qu bng biu thc logic sau vit ra mn hnh: ng: "CORRECT"; Sai: "INCORRECT" Gi : S dng bin ton cc lu kt qu ng so snh vi kt qa a vo. 3. Cu lnh no trong cc cu sau y s dng sai th s kin a. <BODY onClick="doSomething();"> b. <INPUT TYPE=text onFocus="doSomething();"> c. <INPUT TYPE=textarea onLoad="doSomething();"> d. <BODY onUnload="doSomething();"> e. <FORM onLoad="doSomething();"> f. <FORM onSubmit="doSomething();"> 4. iu g xy ra khi thc hin script sau:
<HTML> <HEAD> <TITLE>Exercise 5.4</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM OTHER BROWSERS var name = ""; function welcome() { name = prompt("Welcome to my page! What's Your Name?","name"); } function farewell() { alert("Goodbye " + name + ". Thanks for visiting my page."); } // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </HEAD> <BODY onLoad="welcome();" onUnload="farewell();";> This is my page! </BODY> </HTML>

5. S dng vng lp while m phng cc vng lp for sau:

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

38

a.
for (j = 4; j > 0; j --) { document.writeln(j + "<BR>"); }

b.
for (k = 1; k <= 99; k = k*2) { k = k/1.5; }

c.
for (num = 0; num <= 10; num ++) { if (num == 8) break; }

3.1.13. Tr li 1. S dng cch thc confirm() v cu trc if...then:


<HTML> <HEAD> <TITLE>Execise 5.1</TITLE> <HEAD> <BODY> <P> <SCRIPT LANGUAGE="JavaScript"> var conf=confirm("Click OK to see a wellcome message!") if (conf){ document.write("<IMG SRC='wellcome.jpg'>"); document.write("<BR>Wellcome you come to CSE's class"); } else document.write("What a pity! You have just click Cancel button"); </SCRIPT> </P> </BODY> </HTML>

2. Thc hin hi ngi s dng:


<HTML> <HEAD> <TITLE>Exercise 3.3</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM OTHER BROWSERS // DEFINE VARIABLES FOR REST OF SCRIPT var question="What is 10+10?"; var answer=20; var correct='CORRECT';

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

39

var incorrect='INCORRECT'; // ASK THE QUESTION var response = prompt(question,"0"); // chECK THE ANSWER THE FIRST TIME if (response != answer) { // THE ANSWER WAS WRONG: OFFER A SECOND chAncE if (confirm("Wrong! Press OK for a second chance.")) response = prompt(question,"0"); } else { // THE ANSWER WAS RIGHT: OFFER A SECOND QUESTION if (confirm("Correct! Press OK for a second question.")) { question = "What is 10*10?"; answer = 100; response = prompt (question,"0"); } } // chECK THE ANSWER var output = (response == answer) ? correct : incorrect; // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM OTHER BROWSERS // OUTPUT RESULT document.write(output); // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </BODY> </HTML>

3. Cc cu sai: a, c, e. Cc cu ng: b, d, f 4. Khi chng trnh c chy (load), hm wellcome s thc hin hi tn ngi s dng, lu tn vo bin ton cc name. Khi ngi s dng sang mt a ch URL khc, hm farewell() s thc hin gi mt li cm n ti ngi s dng. 5. S dng vng lp while nh sau: a.
j = 5; while (--j > 0) { document.writeln(j + "<BR>"); }

b.
k = 1; while (k <= 99) { k = k * 2 / 1.5;

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

40

c.
num = 0; while (num <= 10) { if (num++ == 8) break; }

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

41

4.

Cc i tng trong JavaScript

Nh ni JavaScript l ngn ng lp tr nh da trn i tng , nhng khng hng i tng bi v n khng h tr cc lp cng nh tnh tha k. Phn ny ni v cc i tng trong JavaScript v hnh 6.1 ch ra s phn cp cc i tng. Trong s phn cp cc i tng ca JavaScript, cc i tng con thc s l cc thuc tnh ca cc i tng b m. Trong v d v chng trnh x l s kin trc y form tn PHIEU_DIEU_TRAl thuc tnh ca i tng document v trng text AGE l thuc tnh ca form PHIEU_DIEU_TRA. tham chiu n gi tr ca AGE, bn phi s dng:
document.PHIEU_DIEU_TRA.AGE.value

Cc i tng c thuc tnh (properties), phng thc (methods), v cc chng trnh x l s kin (event handlers) gn vi chng. V d i tng document c thuc tnh title phn nh ni dung ca th <TITLE> ca document. Bn cnh bn thy phng thc document.write c s dng trong nhiu v d a vn bn kt qu ra document. i tng cng c th c cc chng trnh x l s kin. V d i tng link c hai chng trnh x l s kin l onClick v onMouseOver. onClick c gi khi c i tng link c kch, onMouseOver c gi khi con tr chut di chuyn qua link. Khi bn ti mt document xung Navigator, n s to ra mt s i tng cng vi nhng gi tr cc thuc tnh ca chng da trn file HTML ca document v mt vi thng tin cn thit khc. Nhng i tng ny tn ti mt cch c cp bc v phn nh chnh cu trc ca file HTML .

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

42

S sau s minh ho s phn cp ca cc i tng ny

Window

Texturea Text

navigator

Plugin

Frame

Layer Link

FileUpload Mime Type Password Hidden Submit Reset Radio Checkbox Button Select Option

document

Image Area

Location

Anchor Applet

History Plugin Form

Hnh 6.1: S 1 - Phn cp i tng Navigator Trong s phn cp ny, cc i tng con chnh l cc thuc tnh ca mt i tng cha. V d nh mt form tn l form1 chnh l mt i tng con ca i tng document v c gi ti l document.form1 Tt c cc trang u c cc i tng sau y: navigator: c cc thuc tnh tn v phin bn ca Navigator ang c s dng, dng cho MIME type c h tr bi client v plug -in c ci t trn client. window: l i tng mc cao nht, c cc thuc tnh thc hin p dng vo ton b ca s. document: cha cc thuc tnh da trn ni dung ca document nh tn, mu nn, cc kt ni v cc forms. location : c cc thuc tnh da trn a ch URL hin thi history: Cha cc thuc tnh v cc URL m client yu cu trc .

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

43

Sau y s m t cc thuc tnh, phng thc cng nh cc chng trnh x l s kin cho tng i tng trong JavaScript.

i tng navigator
i tng ny c s dng t c cc thng tin v trnh duyt nh s phin bn. i tng ny khng c phng thc hay chng trnh x l s kin. Cc thuc tnh appCodeName AppName AppVersion userAgent Xc nh tn m ni ti ca trnh duyt (Atlas). Xc nh tn trnh duyt. Xc nh thng tin v phin bn ca i tng navigator. Xc nh header ca user - agent.

V d V d sau s hin th cc thuc tnh ca i tng navigator


<HTML> <HEAD> <TITLE> Navigator Object Exemple </TITLE> <SCRIPT LANGUAGE= "JavaScript"> document.write("appCodeName = "+navigator.appCodeName + "<BR>"); document.write("appName = "+navigator.appName + "<BR>"); document.write("appVersion = "+navigator.appVersion + "<BR>"); document.write("userAgent = "+navigator.userAgent + "<BR>"); </SCRIPT> </HEAD> <BODY> </BODY> </HTML>

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

44

Hnh 6.2: Minh ho cho i tng Navigator

i tng window
i tng window nh ni trn l i tng mc cao nht. Cc i tng document, frame, v tr u l thuc tnh ca i tng window. 4.1.1. Cc thuc tnh defaultStatus - Thng bo ngm nh hin th ln trn thanh trng thi ca ca s Frames - Mng xc nh tt c cc frame trong ca s. Length - S lng cc frame trong ca s cha m. Name - Tn ca ca s hin thi. Parent - i tng ca s cha m Self - Ca s hin thi. Status - c s dng cho thng bo tm thi hin th ln trn thanh thng thi ca s. c s dng ly hay t li thng bo trng thi v ghi ln defaultStatus. Top - Ca s trn cng. Window - Ca s hin thi. 4.1.2. Cc phng thc alert ("message") -Hin th hp hi thoi vi chui "message" v nt OK.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

45

clearTimeout(timeoutID) -Xa timeout do SetTimeout t. SetTimeout tr li timeoutID windowReference.close -ng ca s windowReference. confirm("message") -Hin th hp hi thoi vi chui "message", nt OK v nt Cancel. Tr li gi tr True cho OK v False cho Cancel. [windowVar = ][window]. open("URL", "windowName", [ "windowFeatures" ] ) - M ca s mi. prompt ("message" [,"defaultInput"]) - M mt hp hi thoi nhn d liu vo trng text. TimeoutID = setTimeout(expression,msec ) - nh gi biu thc expresion sau thi gian msec. V d: S dng tn ca s khi gi ti n nh l ch ca mt form submit hoc trong mt Hipertext link (thuc tnh TARGET ca th FORM v A). Trong v d to ra mt ti ca s th hai, nh nt th nht m mt ca s rng, sau mt lin kt s ti file doc2.html xung ca s mi ri mt nt khc dng ng ca s th hai li, v d ny la vo file window.html:
<HTML> <HEAD> <TITLE>Frame Example </TITLE> </HEAD> <BODY> <FORM> <INPUT TYPE="button" VALUE="Open Second Window" onClick="msgWindow=window.open('','window2','resizable=no,width=200,heigh t=200')"> <P> <A HREF="doc2.html" TARGET="window2"> Load a file into window2 </A> </P> <INPUT TYPE="button" VALUE="Close Second Window" onClick="msgWindow.close()"> </FORM> </BODY> </HTML>

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

46

Hnh 6.3: Minh ho cho i tng ca s 4.1.3. Cc chng trnh x l s kin onLoad - Xut hin khi ca s kt thc vic ti. onUnLoad - Xut hin khi ca s c loi b.

i tng location
Cc thuc tnh ca i tng location duy tr cc thng tin v URL ca document hin thi. i tng ny hon ton khng c cc phng thc v chng trnh x l s kin i km. V d: http:// www.abc.com/ chap1/page2.html#topic3 Cc thuc tnh hash - Tn anchor ca v tr hin thi (v d topic3). Host - Phn hostname:port ca URL (v d www.abc.com ). Ch rng y thng l cng ngm nh v t khi c ch ra. Hostname - Tn ca host v domain (v d www.abc.com ). href - Ton b URL cho document hin ti. Pathname - Phn ng dn ca URL (v d /chap1/page2.html). Port - Cng truyn thng c s dng cho my tnh host, thng l cng ngm nh. Protocol - Giao thc c s dng (cng vi du hai chm) (v d http:). Search - Cu truy vn tm kim c th cui URL cho cc script CGI .

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

47

i tng frame
Mt ca s c th c mt vi frame. Cc frame c th cun mt cch c lp vi nhau v mi frame c URL ring. frame khng c cc chng trnh x l s kin. S kin onLoad v onUnLoad l ca i tng window. 4.1.4. Cc thuc tnh frames - Mng tt c cc frame trong ca s. Name - Thuc tnh NAME ca th <FRAME> Length - S lng cc frame con trong mt frame. Parent - Ca s hay frame cha nhm frame hin thi. self - frame hin thi. Window - frame hin thi. 4.1.5. Cc phng thc clearTimeout (timeoutID) - Xo timeout do setTimeout lp. SetTimeout tr li timeoutID. TimeoutID = setTimeout (expression,msec) - nh gi expression sau khi ht thi gian msec. 4.1.6. S dng Frame 4.1.6.1. a) To mt frame (create) to mt frame, ta s dng th FRAMESET . Mc ch ca th ny l nh ngha mt tp cc frame trong mt trang. V d1: to frame ( hnh 17)
<HTML> <HEAD> <TITLE>Frame Example </TITLE> <FRAMESET ROWS="90%,10%"> <FRAMESET COLS="30%,70%"> <FRAME SRC=CATEGORY.HTM NAME="ListFrame"> <FRAME SRC=TITLES.HTM NAME="contentFrame"> </FRAMESET > <FRAME SRC=NAVIGATOR.HTM NAME="navigateFrame"> </FRAMESET > </HEAD> <BODY> </BODY> </HTML>

S sau hin th cu trc ca cc frame: C 3 frame u trn cng mt ca s cha, mc d 2 trong s cc frame nm trong mt fra meset khc.
Top listFrame (category.html) contentFrame (titles.html) navigatorFrame (navigator.html)
Khoa Toan tin, i hc Quc gia H Ni

JavaScript

48

Bn c th gi ti nhng frame trc bng cch s dng thuc tnh frames nh sau: listFrame chnh l top.frames[0] contentFrame chnh l top.frames[1] navigatorFrame chnh l top.frames[2]

Hnh 6.4: Kt qu vic to frame trong V d 2: Cng ging nh mt s la chn, bn c th to ra mt ca s ging nh v d trc nhng trong mi nh ca hai frame li c mt ca s cha ring t navigateFrame. Mc frameset cao nht c th c nh ngha nh sau:
<HTML> <HEAD> <TITLE>Frame Example </TITLE> <FRAMESET ROWS="90%,10%"> <FRAME SRC=muske13.HTML NAME="upperFrame"> <FRAME SRC=NAVIGATOR.HTM NAME="navigateFrame"> </FRAMESET > </HEAD> <BODY> </BODY> </HTML>

Trong file muske13.html li tip tc t mt frameset:


<HTML> <HEAD>

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

49

<TITLE>Frame Example </TITLE> <FRAMESET COLS="30%,70%"> <FRAME SRC=CATEGORY.HTM NAME="ListFrame"> <FRAME SRC=TITLES.HTM NAME="contentFrame"> </FRAMESET > </HEAD> <BODY> </BODY> </HTML>

Khi kt qu hin th ca v d 2 ging v d 1 nhng s phn cp ca cc frames li khc hn: Bn c th gi ti cc frame trn bng cch s dng thuc tnh mng frames nh sau: upperFrame chnh l top.frames[0]
top listFrame (category.html) upperFrame (muske13.html) contentFrame (titles.html) navigatorFrame (navigator.html)

navigatorFrame listFrame contentFrame

chnh l top.frames[1] chnh l upperFrame.frames[0] hoc top.frames[0].frames[0] chnh l upperFrame.frames[1] hoc top.frames[0].frames[1] b) Cp nht mt frame (update)

4.1.6.2.

Bn c th cp nht ni dung ca mt frame bng cch s dng thuc tnh location t a ch URL v phi nh ch r v tr ca frame trong cu t rc. Trong v d trn, nu bn thm mt dng sau vo navigatorFrame:
<INPUT TYPE="button" VALUE="Titles only" onClick="top.frames[0].location='artist.html'">

th khi nt Titles only c nhn, file artist.html s c ti vo upperFrame, v hai frame listFrame, contentFrame s b ng li nh chng cha bao gi tn ti.

i tng document
i tng ny cha cc thng tin v document hin thi v cung cp cc phng thc a thng tin ra mn hnh. i tng document c to ra bng cp th <BODY> v </BODY>. Mt s cc thuc tnh gn vi th <BODY>. Cc i tng anchor , forms, history, links l thuc tnh ca i tng document. Khng c cc chng trnh x l s kin cho cc frame. S kin onLoad v onUnLoad l cho i tng window.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

50

4.1.7. Cc thuc tnh alinkColor - Ging nh thuc tnh ALINK. anchor - Mng tt c cc anchor trong document. bgColor - Ging thuc tnh BGCOLOR. cookie - S dng xc nh cookie. fgColor - Ging thuc tnh TEXT. forms - Mng tt c cc form trong document. lastModified - Ng y cui cng vn bn c sa. linkColor - Ging thuc tnh LINK. links - Mng tt c cc link trong document. location - URL y ca vn bn. referrer - URL ca vn bn gi n. title - Ni dung ca th <TITLE>. vlinkColor - Ging thuc tnh VLINK. 4.1.8. Cc phng thc document.clear - Xo document hin thi. document.close - ng dng d liu vo v a ton b d liu trong b m ra mn hnh. document.open (["mineType"]) - M mt stream thu thp d liu vo ca cc phwong thc write v writeln. document.write(expression1 [,expression2]...[,expressionN ]) - Vit biu thc HTML ln vn bn trng mt ca s xc nh. document.writeln (expression1 [,expression2] ... [,expressionN] ) Ging phng thc trn nhng khi ht mi biu thc li xung dng.

i tng anchors
anchor l mt on vn bn trong document c th dng lm ch cho mt siu lin kt. N c xc nh bng cp th <A> v </A>. i tng anchor khng c thuc tnh, phng thc cng nh chng trnh x l s kin. Mng anchor tham chiu n mi anchor c tn trong document. Mi anchor c tham chiu bng cch:
document.anchors [index]

Mng anchor c mt thuc tnh duy nht l length xc nh s lng cc anchor trong document, n c th c xc nh nh sau:
document.anchors.length.

i tng forms
Cc form c to ra nh cp th <FORM> v </FORM>. Phn ln cc thuc tnh ca i tng form phn nh cc thuc tnh ca th <FORM>. C mt vi phn t (elements) l thuc tnh ca i tng forms:
button checkbox hidden password
Khoa Toan tin, i hc Quc gia H Ni

JavaScript

51

radio reset select submit text textarea

Cc phn t ny s c trnh by sau. Nu document cha mt vi form, chng c th c tham chiu qua mng forms. S lng cc form c th c xc nh nh sau:
document.forms.length.

Mi mt form c th c tham chiu nh sau:


document.forms[index]

4.1.9. Cc thuc tnh thuc tnh ACTION ca th FORM. elements Mng cha tt c cc thnh phn trong mt form (nh checkbox, trng text, danh sch la chn encoding Xu cha kiu MIME c s dng m ho ni dung ca form gi cho server. length S lng cc thnh phn trong mt form. method Thuc tnh METHOD. target Xu cha tn ca ca s ch khi submit form action 4.1.10. Cc phng thc formName.submit () - Xut d liu ca mt form tn formName ti trang x l. Phng thc ny m phng mt click vo nt submit trn form. 4.1.11. Cc chng trnh x l s kin onSubmit - Chng trnh x l s kin ny c gi khi ngi s dng chuyn d liu t form i.

i tng history
i tng ny c s dng lu gi cc thng tin v cc URL trc c ngi s dng s dng. Danh sch cc URL c lu tr theo th t thi gian. i tng ny khng c chng trnh x l s kin. 4.1.12. Cc thuc tnh length - S lng cc URL trong i tng. 4.1.13. Cc phng thc history.back() - c s dng tham chiu ti URL mi c thm trc y. history.forward() - c s dng tham chiu ti URL k tip trong danh sch. N s khng gy hiu ng g nu n cui ca danh sch.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

52

history.go (delta | "location") - c s dng chuyn ln hay chuyn xung delta bc hay di chun n URL xc nh bi location trong danh sch. Nu delta c s dng th vic dch chuyn ln pha trn khi delta dng v xung pha di khi delta m. nu s dng location, URL gn nht c cha location l chui con s c tham chiu .

i tng links
i tng link l mt on vn bn hay mt nh c xem l mt siu lin kt. Cc thuc tnh ca i tng link ch yu x l v URL ca cc siu lin kt. i tng link cng khng c phng thc no. Mng link cha danh sch tt c cc lin kt trong document. C th xc nh s lng cc link qua document.links.length() C th tham chiu ti mt lin kt qa document.links [index] xc nh cc thuc tnh ca i tng link, c th s dng URL tng t: http://www.abc.com/chap1/page2.html#topic3 4.1.14. Cc thuc tnh hash - Tn anchor ca v tr hin thi (v d topic3). Host - Phn hostname:port ca URL (v d www.abc.com). Ch rng y thng l cng ngm nh v t khi c ch ra. Hostname - Tn ca host v domain (v d ww.abc.com). href - Ton b URL cho document hin ti. Pathname - Phn ng dn ca URL (v d /chap1/page2.html). port - Cng truyn thng c s dng cho my tnh host, thng l cng ngm nh. Protocol - Giao thc c s dng (cng vi du hai chm) (v d http:). Search - Cu truy vn tm kim c th cui URL cho cc script CGI. Target - Ging thuc tnh TARGET ca <LINK>. 4.1.15. Cc chng trnh x l s kin onClick - Xy ra khi ngi s dng nhn vo link. onMouseOver - Xy ra khi con chut di chuyn qua link.

i tng Math
i tng Math l i tng ni ti trong JavaScript. Cc thuc tnh ca i tng ny cha nhiu hng s ton hc, cc hm ton hc, lng gic ph bin. i tng Math khng c chng trnh x l s kin. Vic tham chiu ti number trong cc phng thc c th l s hay cc biu thc c nh gi l s hp l. 4.1.16. Cc thuc tnh E LN2 - Hng s Euler, khong 2,718. - logarit t nhin ca 2, khong 0,693.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

53

LN10 LOG2E

- logarit t nhin ca 10, khong 2,302. - logarit c s 2 ca e, khong 1,442.

PI - Gi tr ca , khong 3,14159. SQRT1_2 - Cn bc 2 ca 0,5, khong 0,707. SQRT2 - Cn bc 2 ca 2, khong 1,414. 4.1.17. Cc phng thc Math.abs ( number ) - Tr li gi tr tuyt i ca number. Math.acos ( number) - Tr li gi tr arc cosine (theo radian) ca number. Gi tr ca number phi nmg gia -1 v 1. Math.asin ( number) - Tr li gi tr arc sine (theo radian) ca number. Gi tr ca number phi nmg gia -1 v 1. Math.atan (number) - Tr li gi tr arc tan (theo radian) ca number. Math.ceil (number) - Tr li s nguyn nh nht ln hn hoc bng number. Math.cos (number) - Tr li gi tr cosine ca number. Math.exp ( number ) - Tr li gi tr e^ number , vi e l hng s Euler. Math.floor (number) - Tr li s nguyn ln nht nh hn hoc bng number. Math.log ( number) - Tr li logarit t nhin ca number. Math.max (num1,num2) - Tr li gi tr ln nht gia num1 v num2 Math.min ( num1,num2) - Tr li gi tr nh nht gia num1 v num2. Math.pos ( base,exponent) - Tr li gi tr base lu tha exponent. Math.random (r) - Tr li mt s ngu nhin gia 0 v 1. Phwong thc ny ch thc hin c trn nn tng UNIX. Math.round (number) - Tr li gi tr ca number lm trn ti s nguyn gn nht. Math.sin ( number) - Tr li sin ca number. Math.sqrt ( number) - Tr li cn bc 2 ca number. Math.tan ( number) - Tr li tag ca number.

i tng Date
i tng Date l i tng c sn trong JavaScript. N cung cp nhiu phng thc c ch x l v thi gian v ngy thng. i tng Date khng c thuc tnh v chng trnh x l s kin. Phn ln cc phng thc date u c mt i tng Date i cng. Cc phng thc gii thiu trong phn ny s dng i tng Date dateVar, v d:
dateVar = new Date ('August 16, 1996 20:45:04');

4.1.18. Cc phng thc dateVar.getDate() - Tr li ngy trong thng (1 -31) cho dateVar. dateVar.getDay() - Tr li ngy trong tun (0=ch nht,...6=th by) cho dateVar.
Khoa Toan tin, i hc Quc gia H Ni

JavaScript

54

dateVar.getHours() - Tr li gi (0 -23) cho dateVar. dateVar.getMinutes() - Tr li pht (0 -59) cho dateVar. dateVar.getSeconds() - Tr li giy (0 -59) cho dateVar. dateVar.getTime() - Tr li s lng cc mili giy t 00:00:00 ngy 1/1/1970. dateVar.getTimeZoneOffset() - Tr li dch chuynbng pht ca gi a phng hin ti so vi gi quc t GMT. dateVar.getYear() -Tr li nm cho dateVar. Date.parse ( dateStr) - Phn tch chui dateStr v tr li s lng cc mili giy tnh t 00:00:00 ngy 01/01/1970. dateVar.s etDay( day) - t ngy trong thng l day cho dateVar. dateVar.s etHours(hours) - t gi l hours cho dateVar. dateVar.s etMinutes(minutes) - t pht l minutes cho dateVar. dateVar.s etMonths( months) - t thng l months cho dateVar. dateVar.s etSeconds(seconds) - t giy l seconds cho dateVar. dateVar.s etTime(value) - t thi gian l value, trong value biu din s lng mili giy t 00:00:00 ngy 01/01/10970. dateVar.s etYear(years) - t nm l years cho dateVar. dateVar.toGMTString() - Tr li chui biu din dateVar di dng GMT. dateVar.toLocaleString() -Tr li chui biu din dateVar theo khu vc thi gian hin thi. Date.UTC (year, month, day [,hours] [,minutes] [,seconds]) - Tr li s lng mili giy t 00:00:00 01/01/1970 GMT.

i tng String
i tng String l i tng c xy dng ni ti trong JavaScript cung cp nhiu phng thc thao tc trn chui. i tng ny c thuc tnh duy nht l di (length) v khng c chng trnh x l s kin. 4.1.19. Cc phng thc str.anchor (name) - c s dng to ra th <A> (mt cch ng). Tham s name l thuc tnh NAME ca th <A>. str.big() - Kt qu ging nh th <BIG> trn chui str. str.blink() - Kt qu ging nh th <BLINK> trn chui str. str.bold() - Kt qu ging nh th <BOLD> trn chui str . str.charAt(a) - Tr li k t th a trong chui str. str.fixed() - Kt qu ging nh th <TT> trn chui str. str.fontcolor() - Kt qu ging nh th <FONTCOLOR = color>. str.fontsize(size) - Kt qu ging nh th <FONTSIZE = size>. str.index0f(srchStr [,index]) - Tr li v tr trong chui str v tr xut hin u tin ca chui srchStr. Chui str c tm t tri sang phi. Tham s index c th c s dng xc nh v tr bt u tm kim trong chui. str.italics() - Kt qu ging nh th <I> trn chui str.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

55

str.lastIndex0f(srchStr [,index]) - Tr li v tr trong chui str v tr xut hin cui cng ca chui srchStr. Chui str c tm t phi sang tri. Tham s index c th c s dng xc nh v tr bt u tm kim trong chui. str.link(href) - c s dng to ra mt kt ni HTML ng cho chhui str. Tham s href l URL ch ca lin kt. str.small() - Kt qu ging nh th <SMALL> trn chui str . str.strike() - Kt qu ging nh th <STRIKE> trn chui str. str.sub() - To ra mt subscript cho chui str, ging th <SUB>. str.substring(a,b) - Tr li chui con ca str l cc k t t v tr th a ti v tr th b. Cc k t c m t tri sang phi bt u t 0. str.sup() - To ra superscript cho chui str , ging th <SUP>. str.toLowerCase() - i chui str thnh ch thng. str.toUpperCase() - i chui str thnh ch hoa.

Cc phn t ca i tng Form


Form c to bi cc phn t cho php ngi s dng a thng tin vo. Khi , ni dung (hoc gi tr) ca cc phn t s c chuyn n mt chng trnh trn server qua mt giao din c gi l Common Gateway Interface(Giao tip qua mt cng chung) gi tt l CGI S dng JavaScript bn c th vit nhng on scripts chn vo HTML ca bn lm vic vi cc phn t ca form v cc gi tr ca chng. Bng ?: Cc phn t ca form Phn t M t L mt nt bm hn l nt submit hay nt reset (<INPUT TYPE="button">) Mt checkbox (<INPUT TYPE="checkbox">) L mt phn t ti file ln cho php ngi s dng gi ln mt file

button checkbox FileUpload hidden password radio reset select submit text

(<INPUT TYPE="file">)
Mt trng n (<INPUT TYPE="hidden">) Mt trng text nhp mt khu m tt c cc k t nhp vo u hin th l du (*)(<INPUT TYPE="password">) Mt nt bm (<INPUT TYPE="radio">) Mt nt reset(<INPUT TYPE="reset">) Mt danh sch la chn (<SELECT><OPTION>option1</OPTION>

<OPTION>option2</OPTION></SELECT>)
Mt nt submit (<INPUT TYPE="submit">) Mt trng text (<INPUT TYPE="text">)

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

56

textArea

Mt trng text cho php nhp vp nhiu dng

<TEXTAREA>default text</TEXTAREA>)

Mi phn t c th c t tn JavaScript truy nhp n chng qua tn 4.1.20. Thuc tnh type Trong mi phn t ca form u c thuc tnh type, l mt xu ch nh r kiu ca phn t c a vo nh nt bm, mt trng text hay mt checkbox... Xu c th l mt trong cc gi tr sau: Text field: "text" Radio button: "radio" Checkbox: "checkbox" Hidden field: "hidden" Submit button: "submit" Reset button: "reset" Password field: "password" Button: "button" Select list: "select-one" Multiple select lists: "select-multiple" Textarea field: "textarea" 4.1.21. Phn t button Trong mt form HTML chun, ch c hai nt bm c sn l submit v reset bi v d liu trong form phi c gi ti mt vi a ch URL (thng l CGI -BIN script) x l v lu tr. Mt phn t button c ch nh r khi s dng th INPUT: <INPUT TYPE="button" NAME="name" VALUE= "buttonName"> Trong th INPUT, name l tn ca button, thuc tnh VALUE c cha nhn ca button s c hin th trn Navigator ca browser. Ch c mt th s kin duy nht i vi button l onClick. Kt hp vi n l cch thc duy nht click.Phn t buttton c kh nng m rng cho php ngi lp trnh JavaScript c th vit c mt on m lnh JavaScript thc thi vic thm vo mt nt bm trong mt script. Trong v d sau, thay v s dng onChange, bn c th chnh sa script nh gi biu thc khi button c bm. V d: nh gi mt form s dng phn t button.
<HTML> <HEAD> <TITLE>button Example</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM OTHER BROWSERS function calculate(form) { form.results.value = eval(form.entry.value); }

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

57

// STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </HEAD> <BODY> <FORM METHOD=POST> Enter a JavaScript mathematical expression: <INPUT TYPE="text" NAME="entry" VALUE=""> <BR> The result of this expression is: <INPUT TYPE=text NAME="results" onFocus="this.blur();"> <BR> <INPUT TYPE="button" VALUE="Calculate" onClick="calculate(this.form);"> </FORM> </BODY> </HTML>

4.1.22. Phn t checkbox Cc phn t checkbox c kh nng bt tt dng chn hoc khng chn mt thng tin. Cc checkbox c nhiu thuc tnh v cch thc hn button. Bng di y l danh sch cc thuc tnh v cc cch thc ca phn t checkbox. Bng . Cc thuc tnh v cch thc ca phn t checkbox. Cch thc v thuc tnh
checked defaultChecked name value click()

M t Cho bit trng thi hin thi ca checkbox (thuc tnh) Cho bit trng thi mc nh ca phn t (thuc tnh) Cho bit tn ca phn t c ch nh trong th INPUT (thuc tnh) Cho bit gi tr hin thi ca phn t c ch nh trong th INPUT (thuc tnh) M t mt click vo checkbox (Cch thc)

Phn t checkbox ch c mt th s kin l onClick V d: To hp checkbox nhp vo mt s ri la chn tnh nhn i v bnh phng:
<HTML> <HEAD> <TITLE>checkbox Example</TITLE> <SCRIPT> <!-- HIDE FROM OTHER BROWSERS function calculate(form,callingField) { if (callingField == "result") { // if(1) if (form.square.checked) { // if(2) form.entry.value = Math.sqrt(form.result.value); }

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

58

else { form.entry.value = form.result.value / 2; } //end if(2) } else{ if (form.square.checked) { // if(3) form.result.value=form.entry.value*form.entry.value; } else { form.result.value = form.entry.value * 2; } //enfzd if(3) }//end if(1) }//end function // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </HEAD> <BODY> <FORM METHOD=POST> Value: <INPUT TYPE="text" NAME="entry" VALUE=0 onChange="calculate(this.form,this.name);"> <BR> Action (default double): <INPUT TYPE=checkbox NAME=square onClick="calculate(this.form,this.name);"> Square <BR> Result: <INPUT TYPE="text" NAME="result" VALUE=0 onChange="calculate(this.form,this.name);"> </FORM> </BODY> </HTML>

Trong script ny, bn thy cch s dng th s kin onClick cng nh thuc tnh checked l mt gi tr kiu Boolean c th dng lm iu kin trong cu lnh if...else Bn c th thm mt checkbox tn l square vo form. Nu hp ny c check, ch ng trnh s ly gi tr ca n, nu khng, mt thc thi c mc nh s nhn i gi tr ca n. Th s kin onClick trong checkbox c nh ngha:
(<INPUT TYPE=checkbox NAME=square onClick= "calculate( this.form, this.name);"> )

Khi nu ngi dng thay i mt cu lnh khc, form s c tnh ton li. to ra s m rng cho checkbox. bn c th thay i hm calculate() nh sau:
function calculate(form,callingField) { if (callingField == "result") { // if (1) if (form.square.checked) { // if (2) form.entry.value = Math.sqrt(form.result.value); }

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

59

} }

else { form.entry.value = form.result.value / 2; //end if(2)

else { if (form.square.checked) { // if (3) form.result.value=form.entry.value*form.entry.value; } else { form.result.value = form.entry.value * 2; } // end if (3) } // end if (1) }

4.1.23. Phn t File Upload Phn t ny cung cp cho form mt cch ngi s dng c th ch r mt file a vo form x l. Phn t file Upload c ch nh r trong JavaScript bng i tng FileUpload. i tng ch c hai thuc tnh l name v value, c hai u l gi tr xu nh cc i tng khc. Khng c cch thc hay th file cho i tng ny. 4.1.24. Phn t hidden Phn t hidden l phn t duy nht trong s tt c cc phn t ca form khng c hin th trn Web browser. Trng hidden c th s dng lu cc gi tr cn thit gi ti server song song vi s xut ra t form (form submission) nhng n khng c hin th trn trang. Mi ngi c th s dng trong JavaScript lu cc gi tr trong sut mt script v tnh ton khng cn form. i tng hidden ch c hai thuc tnh l name v value, cng l nhng gi tr xu ging cc i tng khc. Khng c cch thc hay th s kin no cho i tng ny. 4.1.25. Phn t Password i tng Password l i tng duy nht trong cc i tng ca form m khi g bt k k t no vo cng u hin th du sao(*). N cho php a vo nhng thng tin b mt nh ng k mt khu... i tng Password c 3 thuc tnh ging trng text l: defaultValue, name v value. Khng ging vi hai phn t trn, trng Password c nhiu cch thc hn(focus(), blur(), and select() ) v tng ng vi cc th s kin: onFocus, onBlur, and onSelect. Phn ny s c ni k hn trong i tng text. 4.1.26. Phn t radio i tng radio gn ging s bt tt checkbox khi c hai nt radio kt hp thnh mt nhm. Khi nhiu radio c kt hp thnh mt nhm, ch c mt nt c chn trong bt k mt thi im no. V d dng lnh sau to ra mt nhm radio c ba nt tn l test:
<INPUT TYPE="radio" NAME="test" VALUE="1" chECKED>1<BR> <INPUT TYPE="radio" NAME="test" VALUE="2">2<BR> <INPUT TYPE="radio" NAME="test" VALUE="3">3<BR>

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

60

Nhm cc nt radio li bng cch t cho chng c cng mt tn trong cc th INPUT. C mt vi thuc tnh kim tra trng thi hin thi ca mt nhm nt radio. Bng sau hin th cc thuc tnh v cch thc ca i tng radio. Bng? . Cc thuc tnh v cch thc ca i tng radio. Thuc tnh v cch thc
checked defaultChecked index length name value click()

M t M t trng thi hin thi ca phn t radio (thuc tnh) M t trng thi mc nh ca phn t (thuc tnh) M t th t ca nt radio c chn hin thi trong mt nhm M t tng s nt radio trong mt nhm M t tn ca phn t c ch nh trong th INPUT (thuc tnh) M t gi tr hin thi ca phn t c nh ra trong th INPUT (thuc tnh) M phng mt click trn nt radio (cch thc)

Cng nh checkbox, radio ch c mt th s kin l onClick. Khng c bt k mt i tng form no c thuc tnh index v length. Do mt nhm radio gm nhiu phn t radio, nn chng c t trong mt mng cc nt radio v c nh s t 0. Trong v d nhm radio c tn test trn, nu nhm nm trong mt form c tn l "testform", bn c th gi ti nt radio th hai bng tn "testform.test[1]" v c th kim tra gi tr ca n bng "testform.test[1].checked" minh ho r cch dng i tng radio, ta xem v d sau: V d:
<HTML> <HEAD> <TITLE>radio button Example</TITLE> <SCRIPT> <!-- HIDE FROM OTHER BROWSERS function calculate(form,callingField) { if (callingField == "result") { if (form.action[1].checked) { form.entry.value = Math.sqrt(form.result.value); } else { form.entry.value = form.result.value / 2; } } else { if (form.action[1].checked) { form.result.value=form.entry.value*form.entry.value; } else { form.result.value = form.entry.value * 2; } }

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

61

} // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </HEAD> <BODY> <FORM METHOD=POST> Value: <INPUT TYPE="text" NAME="entry" VALUE=0 onChange="calculate(this.form,this.name);"> <BR> Action:<BR> <INPUT TYPE="radio" NAME="action" VALUE="twice" onClick="calculate(this.form,this.name);"> Double<BR> <INPUT TYPE="radio" NAME="action" VALUE="square" onClick="calculate(this.form,this.name);"> Square <BR> Result: <INPUT TYPE=text NAME="result" VALUE=0 onChange="calculate(this.form,this.name);"> </FORM> </BODY> </HTML>

Trong v d ny, s thay i t checkbox trn l rt kh nhn bit. Thay cho mt checkbox trong v d trc, y ta s dng hai nt radio vi hai gi tr khc nhau: double v square Nh ta bit c th truy nhp n cc nt radio qua mt mng, do hai nt ny c th truy nhp bng action[0] v action[1]. Bng cch ny, bn ch cn thay i tham chiu n hm calculate() t form.square.checked thnh form.action[1].checked. 4.1.27. Phn t reset S dng i tng reset, bn c th tc ng ngc li click vo nt Reset. Cng ging i tng button, i tng reset c hai thuc tnh l name v value, v mt cch thc click(), mt th s kin onClick. Hu ht nhng ngi lp trnh khong s dng th s kin onClick ca nt reset kim tra gi tr ca nt ny, i tng reset thng dng xo form. V d sau minh ho cch s dng nt reset xo cc gi tr ca form. V d:
<HTML> <HEAD> <TITLE>reset Example</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM OTHER BROWSERS function clearForm(form) { form.value1.value = "Form"; form.value2.value = "Cleared"; } // STOP HIDING FROM OTHER BROWSERS --> //SCRIPT>

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

62

</HEAD> <BODY> <FORM METHOD=POST> <INPUT TYPE="text" NAME="value1"><BR> <INPUT TYPE="text" NAME="value2"><BR> <INPUT TYPE="reset" VALUE="Clear Form" onClick="clearForm(this.form);"> </FORM> </BODY> </HTML>

4.1.28. Phn t select Danh sch la chn trong cc form HTML xut hin menu drop -down hoc danh sch cun c ca cc i tng c th c la chn. Cc danh dch c xy dng bng cch s dng hai th SELECT v OPTION. V d:
<SELECT NAME="test"> <OPTION SELECTED>1 <OPTION>2 <OPTION>3 </SELECT>

to ra ba thnh phn ca menu th drop -down vi ba la chn 1,2 v 3. S dng thuc tnh SIZE bn c th to ta mt danh sch cun vi s phn t hin th ln th nht. bt menu drop-down trong mt menu cun vi hai thnh phn hin th, bn c th s dng nh sau:
<SELECT NAME="test" SIZE=2> <OPTION SELECTED>1 <OPTION>2 <OPTION>3 </SELECT>

Trong c hai v d trn, ngi s dng ch c th c mt la chn. Nu s dng thuc tnh MULTIPLE, bn c th cho php ngi s dng la chn nhiu hn mt gi tr trong danh sch la chn:
<SELECT NAME="test" SIZE=2 MULTIPLE> <OPTION SELECTED>1 <OPTION>2 <OPTION>3 </SELECT>

Danh sch la chn trong JavaScript l i tng select. i tng ny to ra mt vi thnh phn tng t cc button v radio. Vi cc thnh phn la chn, danh sch cc la chn c cha trong mt mng c nh s t 0. Trong trng hp ny, mng l mt thuc tnh ca i tng select gi l options. C vic la chn cc option v tng phn t option ring bit u c nhng thuc tnh. B sung thm vo mng option, phn t select c thuc tnh selectedIndex, c cha s th t ca option c la chn hin thi. Mi option trong danh sch la chn u c mt vi thuc tnh:

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

63

DEFAULTSELECTED: cho bit option c c mc nh l la chn trong th OPTION hay khng. INDEX: cha gi tr s th t ca option hn thi trong mng option. SELECTED: cho bit trng thi hin thi ca option TEXT: c cha gi tr ca dng text hin th trn menu cho mi option, v thuc tnh value mi gi tr ch ra trong th OPTION. i tng select khng c cc cch thc c nh ngha sn. Tuy nhin, i tng select c ba th s kin, l onBlue, onFocus, onChange, chng u l nhng i tng text. V d bn c danh sch la chn sau:
<SELECT NAME="example" onFocus="react();"> <OPTION SELECTED VALUE="Number One">1 <OPTION VALUE="The Second">2 <OPTION VALUE="Three is It">3 </SELECT>

Khi ln u tin hin th bn c th truy nhp ti cc thng tin sau:


example.options[1].value = "The Second" example.options[2].text = "3" example.selectedIndex = 0 example.options[0].defaultSelected = true example.options[1].selected = false

Nu ngi s dng kch vo menu v la chn option th hai, th th onFocus s thc hin, v khi gi tr ca thuc tnh s l:
example.options[1].value = "The Second" example.options[2].text = "3" example.selectedIndex = 1 example.options[0].defaultSelected = true example.options[1].selected = true

Sa cc danh sch la chn


Navigator 3.0 cho php thay i ni dung ca danh sch la chn t JavaScript bng c ch lin kt cc gi tr mi cho thuc tnh text ca cc thc th trong danh sch. V d, trong v d trc, bn to ra mt danh sch la chn nh sau:

<SELECT NAME="example" onFocus="react();"> <OPTION SELECTED VALUE="Number One">1 <OPTION VALUE="The Second">2 <OPTION VALUE="Three is It">3 </SELECT> C th thay i c dng text hin th trn nt th hai thnh "two" bng: example.options[1].text = "two"; C th thm cc la chn mi vo danh sch bng cch s dng i tng xy dng Option() theo c php:

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

64

newOptionName = new Option(optionText, optionValue, defaultSelected, selected); selectListName.options[index] = newOptionName; Vic to i tng option() ny vi dng text c ch trc, defaultSelected v selected nh trn nh ra nhng gi tr kiu Boolean. i tng ny c lin kt vo danh sch la chn c thc hin bng index. Cc la chn c th b xo trong danh sch la chn bng cch gn gi tr null cho i tng mun xo selectListName.options[index] = null; 1.1 Phn t submit Nt Submit l mt trng hp c bit ca button, cng nh nt Reset. Nt ny a thng tin hin ti t cc trng ca form ti a ch URL c ch ra trong thuc tnh ACTION ca th form s dng cch thc METHOD ch ra trong th FORM. Ging nh i tng button v reset, i tng submit c sn thuc tnh name v value, cch thc click() v th s kin onClick. 1.2 Phn t Text Phn t ny nm trong nhng phn t hay c s dng nht trong cc form HTML. Tng t nh trng Password, trng text c ho php nhp vo mt dng n, nhng cc k t ca n hin ra bnh thng. i tng text c ba thuc tnh:defautValue, name v value. Ba cch thc m phng s kin ca ngi s dng: focus(), blur() v select(). C 4 th s kin l: obBlur, onFocus, onChange, onSelect. Ch cc s kin ny ch thc hin khi con tr c kch ra ngoi trng text. Bng sau m t cc thuc tnh v cch thc ca i tng text. Bng .Cc thuc tnh v cch thc ca i tng text. Cch thc v thuc tnh M t defaultValue name value focus() blur() select() Ch ra gi tr mc nh ca phn t c ch ra trong th INPUT (thuc tnh) Tn ca i tng c ch ra trong th INPUT (thuc tnh) Gi tr hin thi ca phn t (thuc tnh) M t vic con tr ti trng text (cch thc) M t vic con tr ri trng text (cch thc) M t vic la chn dng text trong trng text (cch thc)

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

65

Mt ch quan trng l c th gn gi tr cho trng text bng cch lin kt cc gi tr vi thuc tnh value. Trong v d sau y, d ng text c a vo trng u tin c lp li trong trng text th hai, v mi dng text c a vo trng text th hai li c lp li trong trng texxt th nht. Kh nng ny ca n c th p dng t ng cp nht hoc thay i d liu. V d. T ng cp nht cc trng text . <HTML> <HEAD> <TITLE>text Example</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM OTHER BROWSERS function echo(form,currentField) { if (currentField == "first") form.second.value = form.first.value; else form.first.value = form.second.value; } // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </HEAD> <BODY> <FORM> <INPUT TYPE=text NAME="first" onChange="echo(this.form,this.name);"> <INPUT TYPE=text NAME="second" onChange="echo(this.form,this.name);"> </FORM> </BODY> </HTML> 1.3 Phn t Textarea Th TEXTAREA cung cp mt hp cho php nhp s dng text do ngi thit k nh trc. V d: <TEXTAREA NAME="fieldName" ROWS=10 COLS=25> Default Text Here </TEXTAREA>

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

66

v d ny to ra mt trng text cho php a vo 10 hng ,mi hng 25 k t. Dng "Defautl Text Here"s xut hin trong trng ny vo ln hin th u tin. Cng nh phn t text , JavaScript cung cp cho bn cc thuc tnh defaultValue, name, v value, cc cch thc focus(), select(), v blur(), cc th s kin onBlur, onForcus, onChange, onSelect. 2. Mng elements[] Cc i tng ca form c th c gi ti bng mng elements[]. V d bn to ra mt form sau: <FORM METHOD=POST NAME=testform> <INPUT TYPE="text" NAME="one"> <INPUT TYPE="text" NAME="two"> <INPUT TYPE="text" NAME="three"> </FORM> bn c th gi ti ba thnh phn ny nh sau: document.elements[0], document.elements[1], document.elements[2], hn na cn c th gi document.testform.one, document.testform.two, document.testform.three. Thuc tnh ny thng c s dng trong cc mi quan h tun t ca cc phn t hn l dng tn ca chng. 3. Mng form[] Cc th s kin c thit k lm vic vi cc form ring bit hoc cc trng mt thi im, n rt hu dng cho php gi ti cc form c lin quan trong cng mt trang. Mng form[] cp n y c th c nhiu xc nh cc nhn ca form trn cng mt trang v have information in a single field match in all three forms. C th gi bng document.forms[] thay v gi bng tn form. Trong script ny, bn c hai trng text nhp v nm trn hai form c lp vi nhau. S dng mng form bn c th tng tc trn cc gi tr ca cc trng trong hai form cng mt lc khi ngi s dng thay i gi tr trn mt form. <HTML> <HEAD> <TITLE>forms[] Example</TITLE> </HEAD> <BODY> <FORM METHOD=POST> <INPUT TYPE=text onChange="document.forms[1].elements[0].value = this.value;">
Khoa Toan tin, i hc Quc gia H Ni

JavaScript

67

</FORM> <FORM METHOD=POST> <INPUT TYPE=text onChange="document.forms[0].elements[0].value = this.value;"> </FORM> </BODY> </HTML> Mt khc, bn cng c th truy nhp n form bng tn form c t trong th FORM: <FORM METHOD=POST NAME="name"> Khi bn c th gi l document.forms["name"] hoc document.name 4. Xem li cc lnh v m rng Lnh/ M rng blur() form.action form.elemrnts Kiu M t cch thc JavaScript M t vic dch chuyn con tr t mt phn t cch thc JavaScript Xu cha gi tr ca thuc tnh ACTION trong th FORM thuc JavaScript thuc JavaScript thuc JavaScript thuc JavaScript thuc JavaScript Th s kin thuc tnh HTML thuc tnh HTML tnh mng cha danh sch cc phn t trong form (nh checkbox, trng text, danh sch la chn) tnh xu cha kiu MIME s dng khi chuyn thng tin t form ti server tnh Xu cha gi tr thuc tnh NAME trong th FORM tnh Xu cha tn ca s ch bi mt form submition tnh nh x kiu ca mt phn t form thnh mt xu. th s kin cho vic submit Thuc tnh kiu cho cc nt bm ca HTML (<INPUT TYPE=button>) Thuc tnh kiu cho cc checkbox ca HTML (<INPUT TYPE=checkbox>)

form.encoding form,name form.target form.submit type onSubmit button checkbox

cch thc JavaScript M t vic submit mt form HTML

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

68

pasword

thuc tnh HTML

Thuc tnh kiu cho cc dng pasword ca HTML(<INPUT TYPE=password>) Thuc tnh kiu cho cc nt radio ca HTML (<INPUT TYPE=radio>) Thuc tnh kiu cho cc nt reset ca HTML (<INPUT TYPE=reset>) Hp th cho danh sch la chn ch ra cc la chn trong danh sch la chn(<SELECT><OPTION>Option 1<OPTION>Option 2</SELECT>) Thuc tnh kiu ca nt submit (<INPUT TYPE=submit>) Thuc tnh kiu ca trng trong form (<INPUT TYPE=text>) Hp th cho nhiu dng text (<TEXTAREA> defautl text </TEXTAREA>)

radio reset SELECT OPTION

thuc tnh HTML thuc tnh HTML th HTML th HTML

submit text TEXTAREA

thuc tnh HTML thuc tnh HTML Th HTML

name value

thuc JavaScript thuc JavaScript

tnh Xu cha tn phn t HTML (button, checkbox, password...) tnh Xu cha gi tr hin thi ca mt phn t HTML(button, checkbox, password...)

click() onClick

cch thc JavaScript M t vic kch vo mt phn t trn form (button, checkbox,password) thuc JavaScript thuc JavaScript thuc JavaScript tnh Th s kin cho s kin kch (button, checkbox, radio button, reset, selection list, submit) tnh Gi tr kiu Boolean m t mt la chn check(checkbox, radio button) tnh Xu cha gi tr mc nh ca mt phn t HTML (password, text, textarea)

checked defaultChecked

focus() blur()

cch thc JavaScript M t vic con tr ti mt phn t (password, text, textarea) cch thc JavaScript M t vic con tr ri khi mt phn

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

69

t (password, text, textarea) select() onFocus() cch thc JavaScript M t vic la chn dng text trong mt trng (password, text, textarea) Th s kin Th s kin cho s kin focus(password, selection list, text, textarea) Th s kin cho s kin blur (password, selection list, text, textarea) Th s kin cho s kin khi gi tr ca trng thay i (password, selection list, text, textarea) Th s kin khi ngi s dng chn dng text trong mt trng (password, text, textarea) tnh L mt s nguyn m t la chn hin thi trong mt nhm la chn (radio button) tnh S nguyn m t tng s cc la chn trong mt nhm cc la chn (radio button) tnh Gi tr Boolean m t khi c mt la chn c t l mc nh (seledtion list) tnh Mng cc la chn trong danh sch la chn tnh Dng text hin th cho mt thnh phn ca menu trong danh sch la chn Hp th cho cc bng HTML Hp th cho cc hng ca mt bng HTML Hp th cho cc ca mt hng trong mt bng HTML L thuc tnh ca th TD m t trong mt ca bng c nhiu ct L thuc tnh ca th TD m t trong

onBlur

Th s kin

onChange

Th s kin

onSelect

Th s kin

index

thuc JavaScript thuc JavaScript thuc JavaScript thuc JavaScript thuc JavaScript th HTML th HTML th HTML

length

dafautlSelected

options text

TABLE TR TD COLSPAN ROWSPAN

thuc tnh HTML thuc tnh HTML

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

70

mt ca bng c nhiu hng BODER thuc tnh HTML L thuc tnh ca th TABLE m t rng ng vin ca bng

document.forms[] thuc JavaScript string.substring()

tnh mng ca cc i tng form vi mt danh sch cc form trong mt document

cch thc JavaScript Tr li mt xu con ca xu string t tham s v tr k t u n v tr k t cui cch thc JavaScript Tr li mt gi tr nguyn tip theo nh hn gi tr ca tham s a vo. thuc JavaScript tnh Gi tr nguyn ca s th t k t cui cng trong xu string

Math.floor() string.length

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

71

5.

M hnh i tng (Object Model)


i tng v thuc tnh

Nh bit, mt i tng trong JavaScript c cc thuc tnh i km vi n. Bn c th truy nhp n cc thuc tnh ca n bng cch gi :
objectName.propertyName

C tn i tng v tn thuc tnh u nhy cm. Bn nh ngha mt thuc tnh bng cch gn cho n mt gi tr. V d, gi s c mt i tng tn l myCar (trong trng hp ny gi s i tng ny tn ti sn sng). Bn c th ly cc thuc tnh c tn make, model v year ca n nh sau:
myCar.make = Ford myCar.model = Mustang myCar.year = 69;

C mt mng lu tr tp hp cc gi tr tham chiu ti tng bin. Thuc tnh v mng trong JavaScript c quan h mt thit vi nhau, thc ra chng ch khc nhau v cch giao tip vi cng mt cu trc d liu. V d cng c th truy nhp ti cc thuc tnh ca i tng myCar trn bng mng nh sau:
myCar[make] = Ford myCar[model] = Mustang myCar[year] = 69;

Kiu mng ny c hiu nh mt mng c kh nng lin kt bi mi mt phn t trong u c th lin kt n mt gi tr xu no . minh ho vic my c thc hin nh th no, hm sau y s hin th cc thuc tnh ca mt i tng thng qua tham s v kiu i tng v tn i tng.
function show_props (obj, obj_name) { var result= for (i in obj) result=result+ obj_name + .+ i+ = + obj[i] + \n return result }

Khi gi hm show_props(myCar,myCar) s hin ln:


myCar.make = Ford myCar.model = Mustang myCar.year = 69;

To cc i tng mi
C JavaScript client -side v server-side u c mt s i tng c nh ngha trc. Tuy nhin, bn cng c th to ra nhng i tng ca ring bn. Trong JavaScript 1.2, nu bn ch mun to ra mt i tng duy nht ca mt kiu i tng, bn c th to n
Khoa Toan tin, i hc Quc gia H Ni

JavaScript

72

bng cch s dng khi to i tng. Hoc nu bn mun to ra nhiu c th ca mt kiu i tng, bn c th to ra mt hm xy dng trc, sau to ra cc i tng c kiu ca hm bng ton t new 5.1.1. S dng khi to i tng Trong nhng phin bn trc ca Navigator, bn ch c th to ra mt i tng bng cch s dng hm xy dng chng hoc s dng mt hm c cung cp bi mt vi i tng khc t c mc ch. Tuy nhin, trong Navigator 4.0, bn c th to ra mt i tng bng cch s dng mt khi to i tng.Bn s dng cch ny khi bn ch mun to ra mt c th n l ch khng phi nhiu c th ca i tng. C php to ra mt i tng bng cch khi to i tng (Object Initializers):
objectName={property1: value1, property2: value2, ..., propertyN: valueN}

Trong objectName l tn ca i tng mi, mi propertyI l mt xc minh (c th l mt tn, mt s hoc mt xu k t) v mi valueI l mt biu thc m gi tr ca n c gn cho propertyI. C th la chn khi to bng tn i tng hoc ch bng cc khai bo. Nu nh bn khng cn dng n i tng trong mi ch, bn khng cn phi gn n cho mt bin. Nu mt i tng c to bng cch khi to i tng mc cao nht, mi ln i tng xut hin trong cc biu thc, JavaScript s nh gi li n mt ln. Ngoi ra, nu s dng vic khi to ny trong mt hm th mi ln gi hm, i tng s c khi to mt ln Gi s bn c cu lnh sau:
if (condition) x={hi: there.}

Trong trng hp ny, JavaScript s to ra mt i tng v gn n vo bin x nu biu thc condition c nh gi l ng Cn v d sau to ra mt i tng myHonda vi 3 thuc tnh: myHonda={color:red,wheels:4,engine:{cylinder:4,size:2.2}} Ch rng thuc tnh engine cng l mt i tng vi cc thuc tnh ca n Trong Navigator 4.0, bn cng c th s dng mt khi to to mt mng. C php to mng bng cch ny khc vi to i tng:
arrayName=[element0, element1,...,elementN]

Trong , arrayName l tn ca mng mi, v mi elementI l gi tr ca phn t v tr ca mng. Khi bn to mt mng bng cch s dng phng php khi to, th n s coi mi gi tr l mt phn t trn mng, v chiu di ca mng chnh l s cc tham s. Bn khng cn phi ch nh r tt c cc phn t trn mng mi. Nu bn t hai du phy vo hng, th mng s c to vi nhng chn trng cho nhng phn t cha c nh ngha nh v d di y: Nu mt mng c to bng cch khi to(initializer) mc cao nht, mi ln mng xut hin trong cc biu thc, JavaScript s nh gi li n mt ln. Ngoi ra, nu s dng vic khi to ny trong mt hm th mi ln gi hm, mng s c khi to mt ln V d1: To mt mng coffees vi 3 phn t v di ca mng l 3:

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

73

coffees = [French Roast,Columbian,Kona]

V d 2: To ra mt mng vi 2 phn t c khi u v mt phn t rng:


fish = [Lion, , Surgeon]

Vi biu thc ny, fish[0] l Lion, fish[2] l Surgeon, v fish[2] cha c nh ngha 5.1.2. S dng mt hm xy dng(Constructor Function) Bn c th to ra i tng ca ring mnh vi hai bc sau: 1. nh ngha kiu ca i tng bng cch vit mt hm xy dng. 2. To ra mt c th ca i tng bng ton t new nh ngha mt kiu i tng, ta phi to ra mt hm ch nh r tn, cc thuc tnh v cc cch thc ca kiu i tng . V d gi s bn mun to mt kiu i tng t vi tn l car, c cc thuc tnh make, model, year v color, thc hin vic ny c th vit mt hm nh sau:
function car(make, model, year ){ this.make = make this.model = model this.year = year }

Ch vic s dng ton t this gn gi tr cho cc thuc tnh ca i tng phi thng qua cc tham s ca hm. V d, bn c th to mt i tng mi kiu car nh sau:
mycar = new car(Eagle,Talon TSi ,1993)

Cu lnh ny s to ra i tng mycar v lin kt cc gi tr c a vo vi cc thuc tnh. Khi gi tr ca mycar.make l Eagle, gi tr ca mycar.model l Talon TSi, v mycar.year l mt s nguyn 1993....C nh vy bn c th to ra nhiu i tng kiu car. Mt i tng cng c th c nhng thuc tnh m bn thn n cng l mt i tng. V d bn nh ngha thm mt i tng khc l person nh sau:
function person(name, age, sex){ this.name=name this.age=age this.sex=sex }

V sau ta to ra hai ngi mi:


rank = new person(Rank McKinnon,33,M) ken = new person(Ken John,39,M)

By gi bn nh ngha li hm xy dng car nh sau:


function car(make, model, year,owner ){ this.make = make this.model = model this.year = year this.owner = owner }
Khoa Toan tin, i hc Quc gia H Ni

JavaScript

74

Nh vy bn c th to i tng kiu car mi:


car1 = new car(Eagle,Talon TSi,1993,rank) car2 = new car(Nissan,300ZX,1992,ken)

Nh vy, thay v phi qua mt xu k t hay mt gi tr s khi to i tng, ta ch cn a hai i tng c to cu lnh trn vo dng tham s ca i tng mi to. Ta cng c th ly c thuc tnh ca i tng owner bng cu lnh sau:
car2.owner.name

Ch rng bn cng c th to ra mt thuc tnh mi cho i tng trc khi nh ngh a n, v d:


car1.color=black

Nh vy, thuc tnh color ca i tng car1 c gn l black. Tuy nhin, n s khng gy tc ng ti bt k mt i tng kiu car no khc. Nu mun thm thuc tnh cho tt c cc i tng th phi nh ngha li hm xy dng i tng. 5.1.3. Lp mc lc cho cc thuc tnh ca i tng Trong Navigator 2.0, bn c th gi thuc tnh ca mt i tng bng tn thuc tnh hoc bng s th t ca n. Tuy nhin t Navigator 3.0 tr i, nu ban u bn nh ngha mt thuc tnh bng tn ca n, bn s lun lun phi gi n bng tn, v nu bn nh ngha mt thuc tnh bng ch s th bn cng lun lun phi gi ti n bng ch s. iu ny ng dng khi bn to mt i tng vi nhng thuc tnh ca chng bng hm xy dng (nh v d v kiu i tng car phn trc) v khi bn nh ngha nhng thuc tnh ca ring mt i tng (nh mycar.color=red). V vy nu bn nh ngha cc thuc tnh ca i tng ngay t u bng ch s nh mycar[5]=25 mpg, bn c th ln lt gi ti cc thuc tnh khc nh mycar[5]. Tuy nhin iu ny l khng ng i vi nhng i tng tng ng ca HTML nh mng form. Bn c th gi ti cc i tng trong mng bi s th t hoc tn ca chng. V d th <FORM> th hai trong mt document c thuc tnh NAME l myform th bn c th gi ti form bng document.form[1] hoc document.form[myForm] hoc document.myForm 5.1.4. nh tng ngha thm cc thuc tnh cho mt kiu i

Bn c th thm thuc tnh cho mt kiu i tng c nh ngha trc bng cch s dng thuc tnh property. Thuc tnh c nh ngha ny khng ch c tc dng i vi mt i tng m c tc dng i vi tt c cc i tng khc cng kiu.V d sau thc hin thm thuc tnh color cho tt c cc i tng kiu car , sau gn mt gi tr mu cho thuc tnh color ca i tng car1:
car.prototype.color=null car1.color=red

5.1.5. nh ngha cc cch thc Mt cch thc l mt hm c lin kt vi mt i tng. Bn nh ngha mt cch thc cng c ngha l bn nh ngha mt hm chun. Bn c th s dng c php sau gn mt hm cho mt i tng ang tn ti:
object.methodname = function_name

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

75

Trong object l i tng ang tn ti, methodname l tn cch thc v function_name l tn hm Bn c th gi cch thc ny t i tng nh sau:
object.methodname(<tham s>)

Bn c th nh ngha cch thc cho mt kiu i tng bng cch a cch thc vo trong hm xy dng i tng. V d bn c th nh ngha mt hm c th nh dng v hin th cc thuc tnh ca cc i tng kiu car xy dng phn trc:
function displayCar () { var result = Abeautiful+this.year+ + this.make + + this.model document.write(result) }

Bn c th thm cch thc ny vo cho i tng car bng cch thm dng lnh sau vo hm nh ngha i tng
this.displayCar= displayCar;

Nh vy c th nh ngha li i tng car nh sau:


function car(make, model, year,owner ){ this.make = make this.model = model this.year = year this.owner = owner this.displayCar= displayCar }

Sau , bn c th gi cch thc displayCar i vi mi i tng:


car1.displayCar() car2.displayCar()

5.1.6. S dng References)

cho

cc

tham

chiu

tng

(Object

JavaScript c mt t kho c bit l this m bn c th s dng n cng vi mt cch thc gi ti i tng hin thi. V d, gi s bn c mt hm validate dng xc nhn gi tr thuc tnh ca mt i tng nm trong mt khong no : function validate(obj, lowval, hival){ if ( (obj.value<lowdate)||(obj.value>hival) ) alert(Invalid value!) } Sau bn c th gi hm validate t mi th s kin onChange: <INPUT TYPE=TEXT NAME=AGE SIZE=3 onChange=validate(this,18,99) > Khi lin kt vi mt thuc tnh form, t kho this c th gi ti form cha ca i tng hin thi. Trong v d sau, myForm c cha i tng Text v mt nt bm. Khi ngi s dng kch vo nt bm, trng text s hin th tn form. Th s kin onClick ca nt bm s dng this.form gi ti form cha l myForm. <FORM NAME=myForm> Form name:<INPUT TYPE=text NAME=text1 VALUE=Beluga> <P>
Khoa Toan tin, i hc Quc gia H Ni

JavaScript

76

<INPUT TYPE=button NAME=button1 value=Show Form Name onClick=this.form.text1.value=this.form.name> </FORM> 5.1.7. Xo i tng Trong JavaScript cho Navigator 2.0, bn khng th xo cc i tng -chng vn tn ti trong khi bn ri khi trang . Trong khi JavaScript cho Navigator 3.0 cho php bn c th xo mt i tng bng cch t cho n tr ti gi tr Null (nu nh l ln cui cng gi ti i tng). JavaScript s ng i tng ngay lp tc thng qua biu thc gn.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

77

6.

Bng tng kt cc t kho

Sau y l cc t oc nh ngha l mt phn trong ngn ng JavaScript v khng c s dng l tn bin: abstract boolean break byte case catch char class const continue default do double else eval extends false final finally float for function goto if implements import in instanceof int interface long native new null package parseFloat parseInt private protected public return short static super switch synchrinized this throw throws transient true try var void while with

Khoa Toan tin, i hc Quc gia H Ni

JavaScript

78

7.

Tng kt

Nh vy, ti liu khng nhng gii thiu s qua v JavaScript, m n cn l sch tham kho ht sc hu ch pht trin ng dng ca bn. Bn c th tham kho ton din JavaScript trong quyn Teach Yourself JavaScript in 14 Days, hoc JavaScript Guide Do JavaScript l ngn ng cn mi v c s thay i nhanh chng, bn nn n vi trang Web ca hng Netscape ( http://www.netscape.com ) c cc thng tin mi nht v ngn ng ny.

Khoa Toan tin, i hc Quc gia H Ni