Vous êtes sur la page 1sur 82

JavaScript 1

ch-ng 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 ch-a phi l cc trang Web ng c kh nng p ng cc s kin t pha ng-i 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 t-ng ng gia Java v JavaScript, nh-ng chng vn l hai ngn ng ring bit. JavaScript l ngn ng d-i 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 d-i 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 t-ng, c ngha l bao gm nhiu kiu i t-ng, v d i t-ng Math vi tt c cc chc nng ton hc. Tuy vy JavaScript khng l ngn ng h-ng i t-ng 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 ng-i 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 ng-i s dng nh- kch chut, nhp vo mt form v iu h-ng trang. V d bn c th kim tra cc gi tr thng tin m ng-i 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 ng-i 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 2

Ch-ng 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:


y y y 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 handler s) 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 tr-c 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 ch-ng 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 t-ng 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> -->

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 3

Dng cui cng ca script cn c du // trnh duyt khng din dch dng ny d-i dng m JavaScript. Cc v d trong ch-ng 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 ph-ng php ny hay hn nhng trc tip mt on lnh JavaScript vo trang HTML). 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 th HTML no. Chng ch -c cha cc cu lnh JavaScript v nh ngha hm.

Ch Khi bn mun ch ra mt xu trch dn trong mt xu khc cn s dng du nhy n ( ' ) phn nh xu . iu ny cho php script nhn ra xu k t .

Tn file ca cc hm JavaScript bn ngoi cn c ui .js, v server s phi nh x ui .js ti kiu MIME application/x-javascript. l nhng g m server gi 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+"%>") }

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 4

2.3. Th <NOScript> v </NOSCRIPT>

Cp th ny dng nh r ni dung thng bo cho ng-i 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. Ng-c 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 ng-i 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.n etscape.com/comprd/mirror/index.html"> Hy kch chut vo y ti v phin bn Netscape mi hn </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

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 5

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, ng-i 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 ng-i 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 tr-ng TEXT v TEXTAREA ca mt form. Trong phn ny, ta s hc cch thc write() v writeln() ca i t-ng document . i t-ng 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 t-ng 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');
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> -->

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 6

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 --> </SCRIPT> </PRE>

Khi duyt s -c kt qu:

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 7

Hnh 2.5: S khc nhau ca write() v writeln()


2.4. Giao tip vi ng-i s dng

JavaScript h tr kh nng cho php ng-i 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 h-ng 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 tr-c. V d: alert("Nhn vo OK tip tc"); Khi file s ch cho n khi ng-i s dng nhn vo nt OK ri mi tip tc thc hin Thng th-ng, cch thc alert() -c s dng trong cc tr-ng hp:
y y y

Thng tin -a v form khng hp l Kt qu sau khi tnh ton khng hp l Khi dch v ch-a sn sng truy nhp d liu

Tuy nhin cch thc alert() mi ch cho php thng bo vi ng-i s dng ch ch-a thc s giao tip vi ng-i s dng. JavaScript cung cp mt cch thc khc giao tip vi ng-i s dng l promt(). T-ng t nh- alert(), prompt() to ra mt hp hi thoi vi mt dng thng bo do bn -a vo, nh-ng ngoi ra n cn cung cp mt tr-ng nhp d liu vo. Ng-i s dng c th nhp vo tr-ng ri

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 8

kch vo OK. Khi , ta c th x l d liu do ng-i s dng va -a vo. V d: Hp hi thoi gm mt dng thng bo, mt tr-ng nhp d liu, mt nt OK v mt nt Cancel Ch-ng trnh ny s hi tn ng-i dng v sau s hin th mt thng bo ngn s dng tn mi -a vo. V d -c l-u vo file Hello.html
<HTML> <HEAD> <TITLE> JavaScript Exemple </TITLE> <SCRIPT LANGUAGE= var JavaScript > ); + name + ! I hope you like name=window.prompt( Hello! What s your name ? ,

document.write( Hello 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 ph-ng 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 ph-ng thc document.write .

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 9

Hnh 2.2: Hin th li cho ng-i nhp

By gi bn c t-ng 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

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 VBSc ript) 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 t heo file HTML c on script

LANGUAGE

//

/*...*/

document.write( )

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 10 document.writel n() alert() Cch thc JavaScript Cch thc ca JavaScript Cch thc JavaScript Tng t cch thc document.write() nhng vit xong t xung dng. Hin th mt dng thng bo trn hp hi thoi Hin th mt dng thng bo trong hp hi thoi ng thi cung cp mt trng nhp d liu ngi s dng nhp vo.

promt()

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 11

Ch-ng 3 Bin trong JavaScript


3.1. Bin v phn loI bin

Tn bin trong JavaScript phi bt u bng ch hay du gch d-i. Cc ch s khng -c s dng m u tn mt bin nh-ng c th s dng sau k t u tin. Phm vi ca bin c th l mt trong hai kiu sau:
y

Bin ton cc: C th -c truy cp t bt k u trong ng dng. -c khai bo nh- sau :

x = 0;
y

Bin cc b: Ch -c truy cp trong phm vi ch-ng 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 ch-ng 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>

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 12 </BODY>

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

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 bn 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:


y y y

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 d-i 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 d-i 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: Hnh 3.1: Kt qu ca x l d liu


y

Phn nguyn thp phn.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 13

y y y

Du chm thp phn (.). 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 .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
y y 1.1.4.

true. false.

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 14

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:
y y y S hc : Nhm l-ng 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, ng-c 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 tr-ng hp ng-c 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 th-ng x=x+y x=x-y x=x*y x=x/y x=x%y Kiu gn rt gn x+=y x-=y x*=y x/=y x%=y

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 15

2.1.2.

So snh

Ng-i 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 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 th-ng, 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 tr-c hay sau ca ++ hay -- vi tn bin (l x trong tr-ng hp ny). Nu ++ ng tr-c x, x s -c tng hoc gim tr-c khi gi tr x -c gn cho y. Nu ++ hay -- ng sau x, gi tr ca x -c gn cho y tr-c 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"

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 16

2.1.5.

Logic

JavaScript h tr cc ton t logic sau y:


expr1 && expr2 expr1 || expr2 ! expr

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.

2.1.6.

Bitwise

Vi cc ton t thao tc trn bit, u tin gi tr -c chuyn d-i dng s nguyn 32 bit, sau ln l-t 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 tr-c 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 chuy n:
<<

Ton t dch tri. Dch chuyn ton hng tri sang tri mt s l-ng 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 l-ng 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 l-ng 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 d-ng kt qu ca ton t >> v >>> l ging nhau.

C mt s ton t dch chuyn bitwise rt gn: Kiu bitwise thng th-ng x = x << y x = x >> y
Khoa Toan tin, i hc Quc gia H Ni

Kiu bitwise rt gn x << = y x - >> y

JavaScript 17

x = x >>> y x=x&y x=x^y x=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 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 18

3.

Cc lnh
y y y

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

Cu lnh iu kin
Cu lnh iu kin cho php ch-ng 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.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 19

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:
y y 3.1.1.

for loop while loop


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 20

Hnh 5.1: Kt qu ca lnh for...loop

V d ny l-u 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 tr-c.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 21

3.1.3.

Break

Cu lnh break dng kt thc vic thc hin ca vng lp for hay while. Ch-ng 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) { if (x<50) break; x++; }

3.1.4.

continue

Lnh continue ging lnh break nh-ng 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 t-ng


JavaScript l mt ngn ng da trn i t-ng, do n c mt s cu lnh lm vic vi cc i t-ng.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 22

3.1.5.

for...in

Cu lnh ny -c s dng lp tt c cc thuc tnh (properties) ca mt i t-ng. 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 t-ng 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"> document.write("The properties of the Window object are: <BR>"); for (var x in window) document.write(" </SCRIPT> </HEAD> <BODY> </BODY> </HTML> "+ x + ", ");

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 23

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 t-ng


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

V d sau to i t-ng person c cc thuc tnh firstname, lastname, age, sex. Ch rng t kho this -c s dng ch i t-ng trong hm person. Sau ba th hin ca i t-ng person -c to ra bng lnh new
<HTML> <HEAD> <TITLE>New Example </TITLE> <SCRIPT LANGUAGE= "JavaScript"> function person(first_name, l ast_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", "Ngu yen Nhat", "24", "Male");

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 24

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. "+ per son3.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

3.1.7.

this

T kho this -c s dng ch i t-ng hin thi. i t-ng -c gi th-ng l i t-ng hin thi trong ph-ng thc hoc trong hm.
C php
this [.property]

C th xem v d ca lnh new.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 25

3.1.8.

with

Lnh ny -c s dng thit lp i t-ng ngm nh cho mt nhm cc lnh, bn c th s dng cc thuc tnh m khng cp n i t- ng.
C php
with (object) { // statement }

V d:

V d sau ch ra cch s dng lnh with thit lp i t-ng ngm nh l document v c th s dng ph-ng thc write m khng cn cp n i t-ng document
<HTML> <HEAD> <TITLE>With Example </TITL E> <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 26

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 t-ng, trong tr-ng hp ny n -c xem nh- l ph-ng thc ca i t-ng . 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 t-ng. Hm printStats -c to ra l ph-ng thc ca i t-ng person
<HTML> <HEAD> <TITLE>Function Example </TITLE> <SCRIPT LANGUAGE= "JavaScript"> function person(first_name, last_name, age, sex)

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 27

{ this.first_name=first_name; this.last_name=last_name; this.age=age; 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>

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 28

1.1.1.1.1.

Hnh 8: V d v hm

Hnh 5.5: Kt qu vic s dng hm

Cc hm c sn
JavaScript c mt s hm c sn, gn trc tip vo chnh ngn ng v khng nm trong mt i t-ng no:
y y y 3.1.9.

eval parseInt parseFloat

eval

Hm ny -c s dng nh gi cc biu thc hay lnh. Biu thc, lnh hay cc i t-ng ca thuc tnh u c th -c nh gi. c bit ht sc hu ch khi nh gi cc biu thc do ng-i dng -a vo (ng-c li c th nh gi trc tip). C php:
returnval=eval (bt k biu thc hay lnh hp l trong Java)

V d:
<HTML>
Khoa Toan tin, i hc Quc gia H Ni

JavaScript 29

<HEAD> <TITLE>Eval Example </TITLE> <SCRIPT LANGUAGE= "JavaScript"> var string=10+ Math.sqrt(64); document.write(string+ =+ eval(string)); </SCRIPT> </HEAD> <BODY> </BODY> </HTML>

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 th-ng -c s dng chuyn cc s nguyn sang c s 10 v m bo rng cc d liu -c nhp d-i dng k t -c chuyn thnh s tr-c khi tnh ton. Trong tr-ng 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.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 30

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> </HTML>

Hnh 5.7: V d parInt


3.1.11. parseFloat

Hm ny ging hm parseInt nh-ng n chuyn chui thnh s biu din d-i dng du phy ng.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 31

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 dif frent 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> </HTML>

Hnh 5.8 : Kt qu ca v d parseFloat

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 32

Mng (Array)
Mc d JavaScript khng h tr cu trc d liu mng nh-ng Netscape to ra ph-ng 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 th-c xc nh tr-c v in cc gi tr 0. Ch rng thnh phn u tin trong mng l di mng v kh ng -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++){ 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>

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 33

Hnh 5.9: V d mng

S kin
JavaScript l ngn ng nh h-ng s kin, ngha l s phn ng tr-c cc s kin xc nh tr-c 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 ch-ng trinh x l s kin) gip cho ch-ng trnh c th phn ng mt cch thch hp.

Ch-ng trnh x l s kin (Event handler): Mt on m hay


mt hm -c thc hin phn ng tr-c mt s kin gi l ch-ng trnh x l s kin. Ch-ng trnh x l s kin -c xc nh l mt thuc tnh ca mt th HTML:
<tagName eventHandler = "JavaScri pt Code or Function">

V d sau gi hm CheckAge() mi khi gi tr ca tr-ng vn bn thay i:


<INPUT TYPE=TEXT NAME="AGE" onChange="CheckAge()">

on m ca ch-ng 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 d-i dng cc hm. Mt s ch-ng trnh x l s kin trong JavaScript:
onBlur onClick

Xy ra khi input focus b xo t thnh phn form Xy ra khi ng-i dng kch vo cc thnh phn hay

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 34

lin kt ca form.
onChange onFocus onLoad onMouseOver onSelect onSubmit onUnLoad

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 ng-i s dng la chn mt tr-ng nhp d liu trn form. Xy ra khi ng-i dng -a ra mt form. Xy ra khi ng-i dng ng mt trang

Sau y l bng cc ch-ng trnh x l s kin c sn ca mt s i t-ng. Cc i t-ng ny s -c trnh by k hn trong phn sau. i t-ng Selection list Text Textarea Button Checkbox Radio button Hypertext link Clickable Imagemap area Reset button Submit button Document Window Framesets Form Image Ch-ng 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 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 ch-ng trnh x l s kin thm nh gi tr -a vo trong tr-ng text. Tui ca ng-i s dng -c nhp vo trong tr-ng ny v ch-ng 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.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 35

Ch-ng trnh x l s kin -c gi mi khi tr-ng AGE b thay i v focus chuyn sang tr-ng 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"> 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">

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 36

<P>

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


i b<INPUT TYPE=CHECKBOX NAME="HOAT_DONG" VALUE="Di bo"> Tr-t tuyt<INPUT TYPE=CHECKBOX NAME="HOAT_ DONG" VALUE="Truot tuyet"> Th thao d-i n-c<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 ng-i 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:
y y y y

Hi ng-i 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 l-u 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 -->
Khoa Toan tin, i hc Quc gia H Ni

JavaScript 38

</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: 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");

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 39

</SCRIPT> </P> </BODY> </HTML>

2. Thc hin hi ng-i 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'; 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">

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 40

<!-- 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 ch-ng trnh -c chy (load), hm wellcome s thc hin hi tn ng-i s dng, l-u tn vo bin ton cc name. K hi ng-i s dng sang mt a ch URL khc, hm farewell() s thc hin gi mt li cm n ti ng-i 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; }

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

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 41

4.

Cc i t-ng trong JavaScript

Nh- ni JavaScript l ngn ng lp trnh da trn i t-ng, nh-ng khng h-ng i t-ng bi v n khng h tr cc lp cng nh- tnh tha k. Phn ny ni v cc i t-ng trong JavaScript v hnh 6.1 ch ra s phn cp cc i t-ng. Trong s phn cp cc i t-ng ca JavaScript, cc i t-ng con th c s l cc thuc tnh ca cc i t-ng b m. Trong v d v ch-ng trnh x l s kin tr-c y form tn PHIEU_DIEU_TRAl thuc tnh ca i t-ng document v tr-ng 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 t-ng c thuc tnh (properties), ph-ng thc (methods), v cc ch-ng trnh x l s kin (event handlers) gn vi chng. V d i t-ng document c thuc tnh title phn nh ni dung ca th <TITLE> ca document. Bn cnh bn thy ph-ng thc document.write -c s dng trong nhiu v d -a vn bn kt qu ra document. i t-ng cng c th c cc ch-ng trnh x l s kin. V d i t-ng link c hai ch-ng trnh x l s kin l onClick v onMouseOver. onClick -c gi khi c i t-ng 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 t-ng cng vi nhng gi tr cc thuc tnh ca chng da trn fil e HTML ca document v mt vi thng tin cn thit khc. Nhng i t-ng 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 t-ng ny

Window

Texturea Text

navigator

Plugin Frame Layer Link document Image Area Location Anchor Applet History Plugin Form Checkbox Button Select Option FileUpload Mime Type Password Hidden Submit Reset Radio

Hnh 6.1: S 1 - Phn cp i t-ng Navigator

Trong s phn cp ny, cc i t-ng con chnh l cc thuc tnh ca mt i t-ng cha. V d nh- mt form tn l form1 chnh l mt i t-ng con ca i t-ng document v -c gi ti l document.form1 Tt c cc trang u c cc i t-ng sau y:
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 t-ng 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 c a document nhtn, mu nn, cc kt ni v cc forms. location: c cc thuc tnh da trn a ch URL hin thi

y y y

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 43

history: Cha cc thuc tnh v cc URL m client yu cu tr-c .

Sau y s m t cc thuc tnh, ph-ng thc cng nh- cc ch-ng trnh x l s kin cho tng i t-ng trong JavaScript.

i t-ng navigator
i t-ng ny -c s dng t -c cc thng tin v trnh duyt nh- s phin bn. i t-ng ny khng c ph-ng thc hay ch-ng trnh x l s kin. Cc thuc tnh Xc nh tn m ni ti ca trnh duyt (Atlas). Xc nh tn trnh duyt. Xc nh thng tin v phin bn ca i t-ng navigator. Xc nh header ca user - agent.

appCodeName AppName AppVersion userAgent

V d V d sau s hin th cc thuc tnh ca i t-ng 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 t-ng Navigator

i t-ng window
i t-ng window nh- ni trn l i t-ng mc cao nht. Cc i t-ng document, frame, v tr u l thuc tnh ca i t-ng window.
4.1.1. y 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 l-ng cc frame trong ca s cha m. Name - Tn ca ca s hin thi. Parent - i t-ng 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.

y y y y y y

y y

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 45

4.1.2. y

Cc ph-ng thc alert ("message") -Hin th hp hi thoi vi chui "message" v nt OK. 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 tr-ng text. TimeoutID = setTimeout(expression,msec ) - nh gi biu thc expresion sau thi gian msec.

y y

V d: S dng tn ca s khi gi ti n nh- l ch ca mt form submit h oc 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 l-a 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, height=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 t-ng ca s


4.1.3. y y Cc ch-ng 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 t-ng location
Cc thuc tnh ca i t-ng location duy tr cc thng tin v URL ca document hin thi. i t-ng ny hon ton khng c cc ph-ng thc v ch-ng tr nh x l s kin i km. V d: http:// www.abc.com/ chap1/page2.html#topic3 Cc thuc tnh
y y 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 th-ng 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, th-ng l cng ngm nh. Protocol - Giao thc -c s dng (cng vi du hai chm) (v d http:).

y y y y

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 47

Search - Cu truy vn tm kim c th cui URL cho cc script CGI.

i t-ng 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 ch-ng trnh x l s kin. S kin onLoad v onUnLoad l ca i t-ng window.
4.1.4. y y y y y y 4.1.5. y Cc thuc tnh frames - Mng tt c cc frame trong ca s. Name - Thuc tnh NAME ca th <FRAME> Length - S l-ng cc frame con trong mt frame. Parent - Ca s hay frame cha nhm frame hin thi. self - frame hin thi. Window - frame hin thi. Cc ph-ng thc clearTimeout (timeoutID) - Xo timeout do setTimeout lp. SetTimeout tr li timeoutID. TimeoutID = setTimeout (expression,msec) expression sau khi ht thi gian msec. S dng Frame 4.1.6.1. a) To mt frame (create)

- nh gi

4.1.6.

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="contentFra me"> </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 frameset khc.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 48

Top listFrame (category.html) contentFrame (titles.html) navigatorFrame (navigator.html) Bn c th gi ti nhng frame tr-c bng cch s dng thuc tnh frames nhsau: 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 tr-c nh-ng 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>
Khoa Toan tin, i hc Quc gia H Ni

JavaScript 49

<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> <TITLE>Frame Example </TI TLE> <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 nh-ng 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 nhsau: top listFrame (category.html) upperFrame (muske13.html) contentFrame (titles.html) navigatorFrame (navigator.html)
upperFrame navigatorFrame listFrame contentFrame

chnh l top.frames[0] 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]

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 50

4.1.6.2.

b) Cp nht mt frame (update)

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 trc. 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, content Frame s b ng li nh- chng ch-a bao gi tn ti.

i t-ng document
i t-ng ny cha cc thng tin v document hin thi v cung cp cc ph-ng thc -a thng tin ra mn hnh. i t-ng document -c to ra bng cp th <BODY> v </BODY>. Mt s cc thuc tnh gn vi th <BODY>. Cc i t-ng anchor, forms, history, links l thuc tnh ca i t-ng document. Khng c cc ch-ng trnh x l s kin cho cc frame. S kin onLoad v onUnLoad l cho i t-ng windo w.
4.1.7. y y y y y y y y y y y y y 4.1.8. y y 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 - Ngy 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. Cc ph-ng 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.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 51

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 ph-ng thc trn nh-ng khi ht mi biu thc li xung dng.

i t-ng 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 t-ng anchor khng c thuc tnh, ph-ng thc cng nh- ch-ng 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 l-ng cc anchor trong document, n c th -c xc nh nh- sau:
document.anchors.length.

i t-ng forms
Cc form -c to ra nh cp th <FORM> v </FORM>. Phn ln cc thuc tnh ca i t-ng form phn nh cc thuc tnh ca th <FORM>. C mt vi phn t (elements) l thuc tnh ca i t-ng forms:
button checkbox hidden password 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 l-ng 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]

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 52

4.1.9. action

Cc thuc tnh

thuc tnh ACTION ca th FORM. Mng cha tt c cc thnh phn trong mt form (nhcheckbox, tr-ng text, danh sch la chn Xu cha kiu MIME -c s dng m ho ni dung ca form gi cho server. S l-ng cc thnh phn trong mt form. Thuc tnh METHOD. Xu cha tn ca ca s ch khi submit form
Cc ph-ng thc

elements encoding length method target 4.1.10.

formName.submit () - Xut d liu ca mt form tn formName ti trang x l. Ph-ng thc ny m phng mt click vo nt submit trn form. 4.1.11. Cc ch-ng trnh x l s kin

onSubmit - Ch-ng trnh x l s kin ny -c gi khi ng-i s dng chuyn d liu t form i.

i t-ng history
i t-ng ny -c s dng l-u gi cc thng tin v cc URL tr-c -c ng-i s dng s dng. Danh sch cc URL -c l-u tr theo th t thi gian. i t-ng ny khng c ch-ng trnh x l s kin.
4.1.12. Cc thuc tnh

length - S l-ng cc URL trong i t-ng. 4.1.13. y Cc ph-ng thc history.back() - -c s dng tham chiu ti URL mi -c thm tr-c 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. 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 d-ng v xung pha d-i khi delta m. nu s dng location , URL gn nht c cha location l chui con s -c tham chiu.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 53

i t-ng links
i t-ng link l mt on vn bn hay mt nh -c xem l mt siu lin kt. Cc thuc tnh ca i t-ng link ch yu x l v URL ca cc siu lin kt. i t-ng link cng khng c ph-ng thc no. Mng link cha danh sch tt c cc lin kt trong document. C th xc nh s l-ng 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 t-ng link, c th s dng URL t-ng t: http://www.abc.com/chap1/page2.html#t opic3
4.1.14. y y 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 th-ng 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, th-ng 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>. Cc ch-ng trnh x l s kin onClick - Xy ra khi ng-i s dng nhn vo link. onMouseOver - Xy ra khi con chut di chuyn qua link.

y y y y

y 4.1.15. y y

i t-ng Math
i t-ng Math l i t-ng ni ti trong JavaScript. Cc thuc tnh ca i t-ng ny cha nhiu hng s ton hc, cc hm ton hc, l-ng gic ph bin. i t-ng Math khng c ch-ng trnh x l s kin. Vic tham chiu ti number trong cc ph-ng thc c th l s hay cc biu thc -c nh gi l s hp l.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 54

4.1.16. y y y y y y y 4.1.17. y y

Cc thuc tnh E LN2 LN10 LOG2E PI

- Hng s Euler, khong 2,718. - logarit t nhin ca 2, khong 0,693. - logarit t nhin ca 10, khong 2,302. - logarit c s 2 ca e, khong 1,442. - Gi tr ca T, khong 3,14159.

SQRT1_2 - Cn bc 2 ca 0,5, khong 0,707. SQRT2

- Cn bc 2 ca 2, khong 1,414.

Cc ph-ng 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 radi an) 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

y
y

bng number.
y y y 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.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 55

y y y

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 t-ng Date
i t-ng Date l i t-ng c sn trong JavaScript. N cung cp nhiu ph-ng thc c ch x l v thi gian v ngy thng. i t-ng Date khng c thuc tnh v ch-ng trnh x l s kin. Phn ln cc ph-ng thc date u c mt i t-ng Date i cng. Cc ph-ng thc gii thiu trong phn ny s dng i t-ng Date dateVar, v d:
dateVar = new Date ('August 16, 1996 20:45:04 ');

4.1.18. y y

Cc ph-ng 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. 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 l-ng cc mili giy t 00:00:00 ngy 1/1/1970. dateVar.getTimeZoneOffset() - Tr li dch chuynbng pht ca gi a ph-ng hin ti so vi gi q uc t GMT. dateVar.getYear() -Tr li nm cho dateVar. Date.parse (dateStr) - Phn tch chui dateStr v tr li s l-ng cc mili giy tnh t 00:00:00 ngy 01/01/1970. dateVar.setDay(day) - t ngy trong thng l day cho dateVar. dateVar.setHours(hours) - t gi l hours cho dateVar. dateVar.setMinutes(minutes) dateVar.

y y y y

y y

y y y

- t pht l minutes cho

y y

dateVar.setMonths(months) - t thng l months cho dateVar. dateVar.setSeconds(seconds) dateVar.

- t giy l seconds cho

dateVar.setTime(value) - t thi gian l value, trong value biu din s l-ng mili giy t 00:00:00 ngy 01/01/10970. dateVar.setYear(years) - t nm l years cho dateVar.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 56

dateVar .toGMTString() - Tr li chui biu din dateVar d-i 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 l-ng mili giy t 00:00:00 01/01/1970 GMT.

i t-ng String
i t-ng String l i t-ng -c xy dng ni ti trong JavaScript cung c p nhiu ph-ng thc thao tc trn chui. i t-ng ny c thuc tnh duy nht l di (length) v khng c ch-ng trnh x l s kin.
4.1.19. y Cc ph-ng thc str.anchor (name) - -c s dng to ra th <A> (mt cch ng). Tham s name l thuc tnh NAME c a th <A>. str.big() -

y y y y y y y y

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

y y

y y y y

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 57

y y y

str.sup() - To ra superscript cho chui str, ging th <SUP>. str.toLowerCase() - i chui str thnh ch th-ng. str.toUpperCase() - i chui str thnh ch hoa.

Cc phn t ca i t-ng Form


Form -c to bi cc phn t cho php ng-i s dng -a thng tin vo. Khi , ni dung (hoc gi tr) ca cc phn t s -c chuyn n mt ch-ng 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

button checkbox FileUpload hidden password radio reset select submit text textArea

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 ng-i s dng gi ln mt file

(<INPUT TYPE="file">)
Mt tr-ng n (<INPUT TYPE="hidden">) Mt tr-ng 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 tr-ng text (<INPUT TYPE="text">)

Mt tr-ng 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

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 58

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 tr-ng 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 (th-ng l CGI -BIN script) x l v l-u 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 ng-i 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 59

} // 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 d-i 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 checkbo x. 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 ph-ng:
<HTML> <HEAD> <TITLE>checkbox Example</TITLE> <SCRIPT>
Khoa Toan tin, i hc Quc gia H Ni

JavaScript 60

<!-- HIDE FROM OTHER BROWSERS function calculate(form,callingField) { if (callingField == "result") { // if(1) // if(2) if (form.square.checked) { } else { form.entry.value = form.result.value / 2; } } else{ if (form.square.checked) { // if(3) form.result.value=form.entry.value*form.entry.value; } else { form.result.value = form.e ntry.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> //end if(2)

form.entry.value = Math.sqrt(form .result.value);

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 61

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 ng-i 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 (2) if (form.square.checked) { } else { form.entry.value = form.result.value / 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) //end if(2)

form.entry.value = Math.sqrt(form.result.value);

4.1.23.

Phn t File Upload

Phn t ny cung cp cho form mt cch ng-i s dng c th ch r mt file -a vo form x l. Phn t file Upload -c ch nh r trong Ja vaScript bng i t-ng FileUpload . i t-ng ch c hai thuc tnh l name v value , c hai u l gi tr xu nhcc i t-ng khc. Khng c cch thc hay th file cho i t-ng 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. Tr-ng hidden c th s dng l-u cc gi tr cn thit gi ti server song song vi s xut ra t form (form submission) nh-ng n khng -c hin th trn trang. Mi ng-i c th s dng trong

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 62

JavaScript l-u cc gi tr trong sut mt script v tnh ton khng cn form. i t-ng hidden ch c hai thuc tnh l name v value , cng l nhng gi tr xu ging cc i t-ng khc. Khng c cch thc hay th s kin no cho i t-ng ny.
4.1.25. Phn t Password

i t-ng Password l i t-ng duy nht trong cc i t-ng 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 t-ng Password c 3 thuc tnh ging t r-ng text l: defaultValue, name v value. Khng ging vi hai phn t trn, tr-ng Password c nhiu cch thc hn(focus(), blur(), and select() ) v t-ng ng vi cc th s kin: onFocus, onBlur, and onSelect. Phn ny s -c ni k hn trong i t- ng text.
4.1.26. Phn t radio

i t-ng 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>

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 t-ng radio. Bng? . Cc thuc tnh v cch thc ca i t-ng radio. Thuc tnh v cch thc
checked defaultChecked index length name value

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)

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 63

click()

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 t-ng 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 t-ng radio, ta xem v d sau: V d:
<HTML> <HEAD> <TITLE>radio button Exam ple</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; } } } // 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>

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 64

<INPUT TYPE="radio" NAME="act ion" 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 tr-c, 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 t-ng reset, bn c th tc ng ng-c li click vo nt Reset. Cng ging i t-ng button, i t-ng reset c hai thuc tnh l name v value, v mt cch thc click(), mt th s kin onClick. Hu ht nhng ng-i lp trnh khong s dng th s ki n onClick ca nt reset kim tra gi tr ca nt ny, i t-ng reset th-ng 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> </HEAD> <BODY>

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 65

<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 t-ng 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, ng-i s dng ch c th c mt la chn. Nu s dng thuc tnh MULTIPLE, bn c th cho php ng-i 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 t-ng select . i t-ng ny to ra mt vi thnh phn t-ng 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 tr-ng hp ny, mng l mt thuc tnh ca i t-ng select gi l options.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 66

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:
y y y y

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 t-ng select khng c cc cch thc -c nh ngha sn. Tuy nhin, i t-ng select c ba th s kin, l onBlue, onFocus, onChange, chng u l nhng i t-ng 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].de faultSelected = true example.options[1].selected = false

Nu ng-i 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 cch lin kt cc gi tr mi cho thuc tnh text ca cc thc th trong danh sch. V d, trong v d tr-c, bn to ra mt danh sch la chn nh- sau:

<SELECT NAME="example" onFocus="react();">

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 67

<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 t-ng xy dng Option() theo c php: newOptionName = new defaultSelected, selected); Option(optionText, optionValue,

selectListName.options[index] = newOptionName; Vic to i t-ng option() ny vi dng text -c ch tr-c, defaultSelected v selected nh- trn nh ra nhng gi tr kiu Boolean. i t-ng 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 t-ng mun xo selectListName.options[index] = null; 1.1 Phn t submit Nt Submit l mt tr-ng hp c bit ca button, cng nh- nt Reset. Nt ny -a thng tin hin ti t cc tr-ng 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 t-ng button v reset, i t-ng 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. T-ng t nh- tr-ng Password, tr-ng text cho php nhp vo mt dng n, nh-ng cc k t ca n hin ra bnh th-ng. i t-ng text c ba thuc tnh:defautValue, name v value. Ba cch thc m phng s kin ca ng-i 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 tr-ng text.
Khoa Toan tin, i hc Quc gia H Ni

JavaScript 68

Bng sau m t cc thuc tnh v cch thc ca i t-ng text. Bng .Cc thuc tnh v cch thc ca i t-ng text. Cch thc v thuc M t tnh 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 t-ng -c ch ra trong th INPUT (thuc tnh) Gi tr hin thi ca phn t (thuc tnh) M t vic con tr ti tr-ng text (cch thc) M t vic con tr ri tr-ng text (cch thc) M t vic la chn dng text trong tr-ng text (cch thc)

Mt ch quan trng l c th gn gi tr cho tr-ng text bng cch lin kt cc gi tr vi thuc tnh value. Trong v d sau y, dng text -c -a vo tr-ng u tin -c lp li trong tr-ng text th hai, v mi dng text -c -a vo tr-ng text th hai li -c lp li trong tr-ng 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 tr-ng 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 -->

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 69

</SCRIPT> </HEAD> <BODY> <FORM> <INPUT TYPE=text onChange="echo(this.form,this.name);"> <INPUT TYPE=text 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 ng-i thit k nh tr-c. V d: <TEXTAREA NAME="fieldName" ROWS=10 COLS=25> Default Text Here </TEXTAREA> v d ny to ra mt tr-ng text cho php -a vo 10 hng ,mi hng 25 k t. Dng "Defautl Text Here"s xut hin trong tr-ng 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[]

NAME="first" NAME="second"

Cc i t-ng 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 document.elements[0], ba thnh phn ny nh- sau: document.elements[1],

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 70

document.elements[2], hn na cn c document.testform.one, document.testform.two, document.testform.three.

th

gi

Thuc tnh ny th-ng -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 tr-ng 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 tr-ng text nhp v nm trn hai form c lp vi nhau. S dng mng form bn c th t-ng tc trn cc gi tr ca cc tr-ng trong hai form cng mt lc khi ng-i s dng thay i gi tr trn mt form. <HTML> <HEAD> <TITLE>forms[] Example</TITLE> </HEAD> <BODY> <FORM METHOD=POST> <INPUT onChange="document.forms[1].elements[0].value this.value;"> </FORM> <FORM METHOD=POST> <INPUT 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:
Khoa Toan tin, i hc Quc gia H Ni

TYPE=text =

TYPE=text =

JavaScript 71

<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 cch JavaScript cch JavaScript thuc JavaScript thuc JavaScript thuc JavaScript thuc JavaScript cch JavaScript thuc JavaScript Th s kin thuc tnh HTML M t thc M t vic dch chuyn con tr t mt phn t thc Xu cha gi tr ca thuc tnh ACTION trong th FORM tnh mng cha danh sch cc phn t trong form (nh- checkbox, tr-ng 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 thc M t vic submit mt form HTML 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>) 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

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

checkbox

thuc tnh HTML

pasword

thuc tnh HTML

radio

thuc tnh HTML

reset

thuc tnh HTML

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 72

ca HTML TYPE=reset>) SELECT OPTION th HTML th HTML

(<INPUT

Hp th cho danh sch la chn ch ra cc la chn trong danh sch la chn(<SELECT><OPTION>Optio n 1<OPTION>Option 2</SELECT>) Thuc tnh kiu ca nt submit (<INPUT TYPE=submit>) Thuc tnh kiu ca tr-ng trong form (<INPUT TYPE=text>) Hp th cho nhiu dng text (<TEXTAREA> defautl text </TEXTAREA>) 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...) thc M t vic kch vo mt phn t trn form (button, checkbox,password) 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) thc M t vic con tr ti mt phn t (password, text, textarea) thc M t vic con tr ri khi mt phn t (password, text, textarea)

submit text TEXTAREA

thuc tnh HTML thuc tnh HTML Th HTML

name value

thuc JavaScript thuc JavaScript cch JavaScript thuc JavaScript thuc JavaScript thuc JavaScript cch JavaScript cch JavaScript

click()

onClick

checked

defaultChecked

focus() blur()

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 73

select()

cch JavaScript Th s kin

thc M t vic la chn dng text trong mt tr-ng (password, text, textarea) 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 tr-ng thay i (password, selection list, text, textarea) Th s kin khi ng-i s dng chn dng text trong mt tr-ng (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

onFocus()

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

thuc tnh HTML

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 74

ROWSPAN

thuc tnh HTML

L thuc tnh ca th TD m t trong mt ca bng c nhiu hng L thuc tnh ca th TABLE m t rng -ng vin ca bng

BODER

thuc tnh HTML

document.forms thuc [] JavaScript string.substring( cch ) JavaScript Math.floor() cch JavaScript thuc JavaScript

tnh mng ca cc i t-ng form vi mt danh sch cc form trong mt document thc Tr li mt xu con ca xu string t tham s v tr k t u n v tr k t cui thc Tr li mt gi tr nguyn tip theo nh hn gi tr ca tham s -a vo. tnh Gi tr nguyn ca s th t k t cui cng trong xu string

string.length

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 75

5.

M hnh i t-ng (Object Model)


i t-ng v thuc tnh

Nh- bit, mt i t-ng 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 t-ng 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 t-ng tn l myCar (trong tr-ng hp ny gi s i t-ng 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 l-u 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 t-ng 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 t-ng thng qua tham s v kiu i t-ng v tn i t-ng.
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;
Khoa Toan tin, i hc Quc gia H Ni

JavaScript 76

To cc i t-ng mi
C JavaScript client-side v server-side u c mt s i t-ng -c nh ngha tr-c. Tuy nhin, bn cng c th to ra nhng i t-ng ca ring bn. Trong JavaScript 1.2, nu bn ch mun to ra mt i t-ng duy nht ca mt kiu i t-ng, bn c th to n bng cch s dng khi to i t- ng. Hoc nu bn mun to ra nhiu c th ca mt kiu i t-ng, bn c th to ra mt hm xy dng tr-c, sau to ra cc i t-ng c kiu ca hm bng ton t new
5.1.1. S dng khi to i t-ng

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

Trong objectName l tn ca i t-ng 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 t-ng hoc ch bng cc khai bo. Nu nh- bn khng cn dng n i t-ng trong mi ch, bn khng cn phi gn n cho mt bin. Nu mt i t-ng -c to bng cch khi to i t-ng mc cao nht, mi ln i t-ng 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 t-ng s -c khi to mt ln Gi s bn c cu lnh sau:
if (condition) x={hi: there.}

Trong tr-ng hp ny, JavaScript s to ra mt i t-ng v gn n vo bin x nu biu thc condition -c nh gi l ng Cn v d sau to ra mt i t-ng 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 t-ng 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 t-ng:
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 ph-ng

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 77

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 ch-a -c nh ngha nh- v d d-i y: Nu mt mng -c to bng cch khi to(initializer) mc cao nht, mi ln mng xut hin trong cc biu thc, JavaScrip t 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:
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] ch-a -c nh ngha
5.1.2. S dng mt hm xy dng(Constructor Function)

Bn c th to ra i t-ng ca ring mnh vi hai b-c sau: 1. nh ngha kiu ca i t-ng bng cch vit mt hm xy dng. 2. To ra mt c th ca i t-ng bng ton t new nh ngha mt kiu i t-ng, ta phi to ra mt hm ch nh r tn, cc thuc tnh v cc cch thc ca kiu i t-ng . V d gi s bn mun to mt kiu i t-ng 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 t-ng phi thng qua cc tham s ca hm. V d, bn c th to mt i t-ng mi kiu car nh- sau:
mycar = new car(Eagle,Talon TSi,1993)

Cu lnh ny s to ra i t-ng 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 nhvy bn c th to ra nhiu i t-ng kiu car. Mt i t-ng cng c th c nhng thuc tnh m bn thn n cng l mt i t-ng. V d bn nh ngha thm mt i t-ng khc l person nh- sau:
function person(name, age, sex){

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 78

this.name=name this.age=age this.sex=sex }

V sau ta to ra hai ng-i 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 }

Nh- vy bn c th to i t-ng 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 t-ng, ta ch cn -a hai i t-ng -c to cu lnh trn vo dng tham s ca i t-ng mi to. Ta cng c th ly -c thuc tnh ca i t-ng owner bng cu lnh sau:
car2.owner.name

Ch rng bn cng c th to ra mt thuc tnh mi cho i t-ng tr-c khi nh ngha n, v d:


car1.color=black

Nh- vy, thuc tnh color ca i t-ng car1 -c gn l black. Tuy nhin, n s khng gy tc ng ti bt k mt i t-ng kiu car no khc. Nu mun thm thuc tnh cho tt c cc i t-ng th phi nh ngha li hm xy dng i t-ng.
5.1.3. Lp mc lc cho cc thuc tnh ca i t-ng

Trong Navigator 2.0, bn c th gi thuc tnh ca mt i t-ng 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 t-ng vi nhng thuc tnh ca chng bng hm xy dng (nh- v d v kiu i t-ng car phn tr-c) v khi

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 79

bn nh ngha nhng thuc tnh ca ring mt i t-ng (nhmycar.color=red). V vy nu bn nh ngha cc thuc tnh ca i t-ng ngay t u bng ch s nh- mycar[5]=25 mpg, bn c th ln l-t gi ti cc thuc tnh khc nh- mycar[5]. Tuy nhin iu ny l khng ng i vi nhng i t-ng t-ng ng ca HTML nh- mng form. Bn c th gi ti cc i t-ng 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 ngha thm cc thuc tnh cho mt kiu i t-ng

Bn c th thm thuc tnh cho mt kiu i t-ng -c nh ngha tr-c bng cch s dng thuc tnh property. Thuc tnh -c nh ngha ny khng ch c tc dng i vi mt i t-ng m c tc dng i vi tt c cc i t-ng khc cng kiu.V d sau thc hin thm thuc tnh color cho tt c cc i t-ng kiu car, sau gn mt gi tr mu cho thuc tnh color ca i t-ng 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 t-ng. 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 t-ng ang tn ti:
object.methodname = function_name

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

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

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

Nh- vy c th nh ngha li i t-ng car nh- sau:


function car(make, model, year,owner ){

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 80

this.make = make this.model = model this.year = year this.owner = owner this.displayCar= displayCar }

Sau , bn c th gi cch th c displayCar i vi mi i t-ng:


car1.displayCar() car2.displayCar()

5.1.6.

S dng cho cc tham chiu i t-ng (Object References)

JavaScript c mt t kho c bit l this m bn c th s dng n cng vi mt cch thc gi ti i t-ng hin thi. V d, gi s bn c mt hm validate dng xc nhn gi tr thuc tnh ca mt i t-ng 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 t-ng hin thi. Trong v d sau, myForm c cha i t-ng Text v mt nt bm. Khi ng-i s dng kch vo nt bm, tr-ng 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> <INPUT TYPE=button NAME=button1 value=Show Form Name onClick=this.form.text1.value=this.form.name> </FORM>
5.1.7. Xo i t-ng

Trong JavaScript cho Navigator 2.0, bn khng th xo cc i t-ng -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 t-ng bng cch t cho n tr ti gi tr Null (nu nh- l ln cui cng gi ti i t-ng). JavaScript s ng i t-ng ngay lp tc thng qua biu thc gn.

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 81

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 d new null package parseFloat parseInt private protected public return short this throw throws transient true try var void while with static super switch synchrinize

Khoa Toan tin, i hc Quc gia H Ni

JavaScript 82

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