var iNum1=10;
var fNum2=10.1;
alert(iNum1.toString()); //10
alert(fNum2.toString()); //10.1
iNum1=parseInt("1234blue"); //1234
var iNum2=parseInt("22.82"); //23
var iNum3=parseInt("blue");
alert(iNum1+iNum2);
alert(iNum3); //NaN
2. String
var oString=new String("Hello World");
var c=oString.charAt(0); //H
var code=oString.charCodeAt(0);
document.writeln(c+" "+code);
var pos=oString.indexOf("World"); //6
document.writeln(pos);
var substring=oString.substring(2,5);
document.writeln(substring); //llo
var upperCase=oString.toUpperCase();
document.writeln(upperCase);
document.writeln(oString instanceof String); //true
Functions
function functionName(arg0,arg1,…argN)
{
Statements
}
function diff(iNum1,iNum2)
{
if(iNum1>iNum2)
return iNum1-iNum2;
else
return iNum2-iNum1;
}
var a=prompt("Please Enter a Number");
var b=prompt("Please Enter Another Number");
if(!isNaN(a)&&!isNaN(b))
document.writeln(diff(parseInt(a),parseInt(b)));
else
document.write("You didn't input a number");
Arguments Object
//Use Arguments object you needn’t specify the name of parameters but you can access //them
function sum()
{
var len=arguments.length;
var sum=0;
for(i=0;i<len;i++)
{
sum+=arguments[i];
}
return sum;
}
document.write(sum(1,2,3,4,5)); //15
5. Function Class (Function as an object)
var function_name=new Function(arg1,arg2,…,argN,function_body)
var f1=new Function("a","b","return a+b");
document.writeln(f1(2,3)); //5
document.write(f1.length+" "+f1.toString());
// 2 function anonymous(a, b) { return a + b; }
Arrays
//how to declare and access an array and arrays can be added
var aColors=new Array();
aColors[0]="red";
aColors[1]="green";
aColors[2]="black";
aColors[5]="wow";
var output=aColors.join(",");
document.write(output+"<br/>");
var aValues=new Array(1,2,3);
var aSum=aColors+aValues;
document.write(aSum.toString());
// red,green,black,,,wow
//red,green,black,,,wow1,2,3
//stack can be used as a stack
var stack=new Array();
stack.push("apple");
stack.push("banana");
stack.push("pear");
document.write(stack.toString());
var item=stack.pop();
document.write(item);
// apple,banana,pearpear
//array also has some other useful functions
stack.reverse();
alert(stack.toString()); //banana,apple
var names="Jack,Green,Mike,Lee";
var aName=names.split(",");
alert(aName.length); //4
7. Date
var d=new Date(); //current date time
document.writeln(d.toDateString()+" "+d.toTimeString());
document.writeln(d.getDate());
document.writeln(d.getTime());
var my=new Date(Date.parse("2008/04/02 12:30:01")); //varies from place to place
var utcDate=new Date(Date.UTC(2004,1,5,13,5));
document.writeln(my);
document.writeln(utcDate);
8. Variable Domains
//JavaScript has local variables but no private varibles
function A()
{
var A1;
A1=1;
}
A.A2=2;
A();
// document.write(A1); inaccessible
// document.write(A.A1); inaccessible
document.write(A.A2);
9. Define New Class and Object
//Constructor Method,this method make all the objects point to different functions,although the contents of the functions are the same.
function Car(sColor,iDoors,iMpg)
{
this.color=sColor;
this.doors=iDoors;
this.mpg=iMpg;
this.showColor=function(){ alert(this.color);};
}
var oCar1=new Car("red",4,32);
var oCar2=new Car("Cyan",2,400);
oCar1.showColor();
oCar2.showColor();*/
//prototype Method,this method make all the objects share the same property,when the property is a reference of other object,problem will occur
function Car()
{}
Car.prototype.color="red";
Car.prototype.doors=3;
Car.prototype.mpg=33;
Car.prototype.showColor=function(){alert(this.color)};
var oCar1=new Car();
oCar1.showColor();
//mixed Method,is the better way to define a class. It uses constructor method to create properties while prototype method to create methods,which avoids all the problems
function Car(sColor,iDoors,iMpg)
{
this.color=sColor;
this.doors=iDoors;
this.mpg=iMpg;
this.drivers=new Array("Jack,Susan");
}
Car.prototype.showColor=function(){alert(this.color)};
var oCar1=new Car("red",4,23);
var oCar2=new Car("blue",2,35);
oCar1.drivers.push("Yin");
alert(oCar1.drivers);
alert(oCar2.drivers);
10 Modify Exist Class
Number.prototype.abs=function(){return parseInt(this)>0?parseInt(this):-parseInt(this);};
Function.prototype.toString=function(){return "Function Content Hidden";};
var n=-2;
document.write(n.abs());
document.write(Math.exp.toString());
11 Inheritance
//ECMA doesn’t specify how to implenment inheritance,by using the following code(object masquerading),one can simulate inheritance.
function A(sColor)
{
this.color=sColor;
this.sayColor=function(){alert(this.color);};
}
function B(sColor,sName)
{
this.newMethod=A;
this.newMethod(sColor);
delete this.newMethod;
this.name=sName;
this.sayName=function(){alert(this.name);};
}
var b=new B("red","son of A");
b.sayName();
b.sayColor();
//Also,one can use prototype chain to simulate inheritance
function A(){}
A.prototype.color="red";
A.prototype.sayColor=function(){alert(this.color);};
function B(){}
B.prototype=new A();
B.prototype.name="Son of A";
B.prototype.sayName=function(){alert(this.name);};
var b=new B();
b.sayColor();
b.sayName();
//prototype chain method can not pass parameters,like 9 Define new Class and Object,the best way is to mix the two methods together
//call() uses first parameter as the “this” inside the function body,other parameters as the functions parameters
function A(sColor)
{
this.color=sColor;
}
A.prototype.sayColor=function(){alert(this.color);};
function B(sColor,sName)
{
A.call(this,sColor);
this.name=sName;
}
B.prototype=new A();
B.prototype.sayName=function(){alert(this.name);};
var b=new B("green","Son of A");
b.sayColor();
b.sayName();
12 setInterval and setTimeout
var iNum=0;var iMax=10;
function inc2()
{
iNum++;
alert(iNum);
if(iNum<=iMax)
setTimeout(inc2,500);
}
setTimeout(inc2,500);
//Also you can use setInterval
var iNum=0;var iMax=10;
var iInterval=null;
function inc()
{
iNum++;
alert(iNum);
if(iNum>iMax)
{
alert("clearing");
clearInterval(iInterval);
}
}
14 Document Object
<body>
<a href="1.htm" id="link1">link1</a>
<a href="2.htm" id="link2">link2</a>
<a href="3.htm" id="link3">link3</a>
<script type="text/javascript">
document.write("<br/>"+document.links.length);
document.write("<br/>"+document.links[0].href);
// document.write("<br/>"+document.links["link2"].href); Mozilla
document.write("<br/>"+document.links("link2").href); //IE
</script>
</body>
15 Access DOM Element
//Only work in IE,MF treats text node a little different
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
</head>
<body>
<p id="firstLine">Hello World!</p>
<p>Isn't it exciting?</p>
<p>You are learning to use DOM</p>
</body>
<script type="text/javascript">
var oHtml=document.documentElement;
var oHead=oHtml.firstChild;
var oBody=oHtml.lastChild;
alert(oBody.childNodes.length);
var firstP=oBody.childNodes.item(0);
var secondP=oBody.childNodes.item(1);
var thirdP=oBody.childNodes.item(2);
alert(oHtml.nodeName);
alert(firstP.nodeName);
alert(secondP.nodeName);
alert(thirdP.nodeName);
firstP.attributes.getNamedItem("id").nodeValue="new_id";
var sid=firstP.attributes.getNamedItem("id");
alert(sid.nodeValue);
</script>
</html>
16 Create New Nodes
//only works in MF
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script type="text/javascript">
function modify()
{
var odiv=document.createElement("div");
var att=document.createAttribute("style");
att.nodeValue="color:red";
odiv.attributes.setNamedItem(att);
var otext=document.createTextNode("It's a New World!");
odiv.appendChild(otext);
var oldP=document.body.getElementsByTagName("p")[0];
document.body.insertBefore(odiv,oldP);
}
function insertNode()
{
var op=document.createElement("p");
var otext=document.createTextNode("Hello world");
op.appendChild(otext);
document.body.appendChild(op);
}
</script>
</head>
<body onload="insertNode()">
<script type="text/javascript">
setTimeout(modify,1000);
</script>
</body>
</html>
17 An Easier Way to Access Attributes
//only works in IE
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script type="text/javascript">
function changeColor()
{
mydiv.className="redDIV"; //className is actually class in HTML
mydiv.style.textDecoration="underline";
}
</script>
<style type="text/css">
.redDIV{ color:Red;}
</style>
</head>
<body onload="changeColor()">
<div id="mydiv">Hello world</div>
</body>
</html>
10 Simple Regular Expression
var sToMatch="cat";
var reCat=/cat/;
alert(reCat.test(sToMatch)); //true
var sToMatch2="a bat, a Cat, a fAt baT, a faT cat";
var reAt=/At/gi; //global and case insensitive
alert(sToMatch2.match(reAt)); //an array
alert(sToMatch2.search(reAt)); //3
11.Simple Pattern
var sToMatch="a bat, a Cat, a fAt baT, a faT cat";
var reBatCatRat=/[bcf]at/gi;
var res1=sToMatch.match(reBatCatRat);
document.write(res1);
var reFat=/[^bc]at/gi;
var res2=sToMatch.match(reFat);
document.write("<br/>"+res2);
/* other patterns
combination class: [a-m1-4/n] anything is in a to m or 1 to 4 or /n
predefined class: . :any character except /n and /r
/d: [0-9]
/D:[^0-9]
/s:[/t/n/x0B/f/r] blank characters
/S: none blank characters
/w:[a-zA-Z_0-9]
/W: [^/w]
*/
/*
Quantifier
Greedy Quantifier:
? 0 or 1 time
* any time
+ at least once
{n} exactly n times
{n,m} at least n times but no more than m times
{n,} at least n times
if you add a ? after Greedy Quantifier it becomes Reluctant Quantifier,such as ??,*?
Greedy quantifiers are considered "greedy" because they force the matcher to read in, or eat, the entire input string prior to attempting the first match. If the first match attempt (the entire input string) fails, the matcher backs off the input string by one character and tries again, repeating the process until a match is found or there are no more characters left to back off from. Depending on the quantifier used in the expression, the last thing it will try matching against is 1 or 0 characters.
The reluctant quantifiers, however, take the opposite approach: They start at the beginning of the input string, then reluctantly eat one character at a time looking for a match. The last thing they try is the entire input string.
*/
var sToMatch1="saasaaaaa";
var regGreedy=/sa*/g;
var regReluctant=/sa*?/g;
document.writeln("<br/>"+sToMatch1.match(regGreedy));
document.writeln("<br/>"+sToMatch1.match(regReluctant));
/*The result is:
bat,Cat,fAt,baT,faT,cat
fAt,faT
saa,saaaaa
s,s
*/
12 Complex Mode
var reg1=/(dog){2}/g //group, matches dogdog
var reg2=/(dog)|(cat)/g //matches dog or cat
var s="dogcatdogdog";
document.write(s.match(reg1));
document.write("<br/>"+s.match(reg2));
/*
Boundary:
^ start of a line
$ end of a line
/b boundary of a word
/B boundary of a non word
*/
var sToMatch="bat, a Cat, a fAt baT, a faT cat";
var reg3=/^bat/gi;
var reg4=/[^b]at/gi;
document.write("<br/>"+sToMatch.match(reg3));
document.write("<br/>"+sToMatch.match(reg4));
var reg5=/cat$/;
document.write("<br/>"+sToMatch.match(reg5));
/*The result is:
dogdog
dog,cat,dog,dog
bat
Cat,fAt,faT,cat
cat*/
13 Add Events in IE
<head>
<title>Untitled Page</title>
<script type="text/javascript">
var fnClick=function(){
alert("Clicked");
}
//Or it can be:
//function fnClick()
// {
// alert("Clicked");}
function addEvent()
{
var oDiv=document.getElementById("Div");
oDiv.attachEvent("onclick",fnClick);
}
</script>
</head>
<body onload="addEvent()">
<div id="Div">Click me</div>
</body>
14 Add Events in DOM(MF)
<head>
<title>Untitled Page</title>
<script type="text/javascript">
var fnClick=function(){
alert("Clicked");
};
function AddEvent()
{
oDiv=document.getElementById("Div");
oDiv.addEventListener("click",fnClick,false);
}
</script>
</head>
<body onload="AddEvent()">
<div id="Div">Click Me</div>
</body>
15 Events in Common
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script type="text/javascript">
function HandleEvent(oEvent)
{
oEvent=oEvent||window.event; document.body.appendChild(document.createElement("p").appendChild(document.createTextNode(oEvent.type+" ")));
}
function getKeyInfo(oEvent)
{
oEvent=oEvent||window.event;
document.getElementById("Div").innerHTML+=oEvent.keyCode+" ";
}
function init()
{
document.getElementById("Div").οnclick=HandleEvent;
document.getElementById("Div").οndblclick=HandleEvent;
document.getElementById("Div").οnkeydοwn=HandleEvent;
document.getElementById("Div").οnkeypress=HandleEvent;
document.getElementById("Div").οnmοusedοwn=HandleEvent;
document.getElementById("Div").οnmοuseup=HandleEvent;
document.getElementById("Div").οnmοuseοver=HandleEvent;
document.body.οnkeydοwn=getKeyInfo;
}
</script>
</head>
<body onload="init();">
<div id="Div" ><br />Hello world</div>
<p>
<input id="Text1" type="text" /></p>
</body>
</html>
16 Mouse Events
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script type="text/javascript">
function handleEvent(oEvent)
{
oEvent=oEvent||window.event;
var oTextBox=document.getElementById("txt1");
oTextBox.value+="/n>"+oEvent.type;
oTextBox.value+="/n target is"+(oEvent.target||oEvent.srcElement).id;
oTextBox.value+="/n at("+oEvent.clientX+","+oEvent.clientY+") in the client";
oTextBox.value+="/n button down is "+oEvent.button;
var arrKeys=[];
if(oEvent.shiftKey){
arrKeys.push("Shift");
}
if(oEvent.ctrlKey)
arrKeys.push("Ctrl");
if(oEvent.altKey)
arrKeys.push("Alt");
oTextBox.value+="/n keys down are: "+arrKeys;
}
function Button1_onclick() {
txt1.value="";
return false;
}
</script>
<style type="text/css">
#txt1
{
height: 511px;
}
</style>
</head>
<body>
<p> Use you rmouse to click and double click the red square</p>
<div style="width:150px; height:150px;background-color:Red;"
onmouseover="handleEvent(event)"
onmouseout="handleEvent(event)"
onclick="handleEvent(event)"
ondblclick="handleEvent(event)"
onmousedown="handleEvent(event)"
onmouseup="handleEvent(event)" id="MyDiv"></div>
<p><textarea id="txt1" cols="100"></textarea><input id="Button1" type="button"
value="Clear" onclick="return Button1_onclick()" /></p>
</body>
</html>
17 HTML Event (onscroll)
//only work in IE
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script type="text/javascript">
window.οnscrοll=function(){
var oWarterMark=document.getElementById("divWaterMark");
scrollPos=document.documentElement.scrollTop;
oWarterMark.style.top=scrollPos; //this may be what MF does not support
}
</script>
</head>
<body>
<p>Try scroll this window</p>
<div id="divWaterMark" style="position:absolute;top:0px;right:0px;color:#cccccc;width:150px;height:30px;background-color:Navy">
WaterMark
</div>
<p>Lines</p>
…… //many lines go here so that the window can be scrolled
<p>Lines</p>
</body>
</html>
18 Cross Platform Events
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script type="text/javascript">
var ISIE=(navigator.userAgent.indexOf("MSIE")>-1);
var ISMF=(navigator.userAgent.indexOf("FireFox")>-1);
var ISOpera=(navigator.userAgent.indexOf("Opera")>-1);
var ISWindows=(navigator.userAgent.indexOf("Windows")>-1);
var EventUtil=new Object;
EventUtil.addEventHandler=function(oTarget,sEventType,fnHandler)
{
if(oTarget.addEventListener)
oTarget.addEventListener(sEventType,fnHandler,false);
else
if(oTarget.attachEvent)
oTarget.attachEvent("on"+sEventType,fnHandler);
else oTarget["on"+sEventType]=fnHandler;
}
EventUtil.removeEventHandler=function(oTarget,sEventType,fnHandler)
{
if(oTarget.removeEventListener)
oTarget.removeEventListener(sEventType,fnHandler,false);
else
if(oTarget.dettachEvent)
oTarget.dettachEvent("on"+sEventType,fnHandler);
else oTarget["on"+sEventType]=null;
}
EventUtil.formatEvent=function(oEvent)
{
if(ISIE&&ISIE)
{
oEvent.charCode=(oEvent.type=="keypress")?oEvent.keyCode:0;
oEvent.eventPhase=2;
oEvent.isChar=(oEvent.charCode>0);
oEvent.pageX=oEvent.clientX+document.documentElement.scrollLeft;
oEvent.pageY=oEvent.clientY+document.documentElement.scrollTop;
oEvent.preventDefault=function(){
this.returnvalue=false;
}
if(oEvent.type=="mouseout")
{
oEvent.relatedTarget=oEvent.toElement;
}
else if(oEvent.type=="mouseover")
{
oEvent.relatedTarget=oEvent.fromElement;
}
oEvent.stopPropagation=function()
{
this.cancelBubble=true;
}
oEvent.target=oEvent.srcElement;
oEvent.time=(new Date).getTime();
}
return oEvent;
}
EventUtil.getEvent=function()
{
if(window.event)
{
return this.formatEvent(window.event);
}
else
{
return EventUtil.getEvent.caller.arguments[0];
}
}
function handleEvent()
{
var oEvent=EventUtil.getEvent();
var oTextbox=document.getElementById("txt1");
oTextbox.value+="/n> event type is:"+oEvent.type;
oTextbox.value+="/n target is "+ oEvent.target.tagName;
if(oEvent.relatedTarget)
{
oTextbox.value+="/n related target is:"+oEvent.relatedTarget.tagName;
}
}
EventUtil.addEventHandler(window,"load",function(){
var oDiv=document.getElementById("div1");
EventUtil.addEventHandler(oDiv,"mouseover",handleEvent);
EventUtil.addEventHandler(oDiv,"mousedown",handleEvent);
EventUtil.addEventHandler(oDiv,"mouseup",handleEvent);
EventUtil.addEventHandler(oDiv,"click",handleEvent);
});
</script>
</head>
<body>
<div>
<div id="div1" style=" width:150px;height:150px; background-color:Gray; float:left" onmouseout="handleEvent(event)">Click here</div>
<div id="div2" style=" width:150px;height:150px; background-color:Green" ></div>
</div>
<p><textarea id="txt1" rows="15" cols="50"></textarea></p>
</body>
</html>
19 Simple Style Control
<head>
<title>Untitled Page</title>
</head>
<body>
<div id="div1" style="background-color:Red; height:150px; width:150px"
onmouseover="this.style.backgroundColor='blue'"
onmouseout="this.style.backgroundColor='red'"></div>
</body>
</html>
20 Mouse Suggestion
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script type="text/javascript">
function showTip(oEvent)
{
oEvent=oEvent?oEvent:window.event;
var oDiv=document.getElementById("divTip1");
oDiv.style.visibility="visible";
oDiv.style.left=oEvent.clientX+5+'px'; //ATTENION HERE,MF MUST HAS THIS KIND OF VALUE, PX CAN NOT BE OMITTED.
oDiv.style.top=oEvent.clientY+5+'px';
}
function hideTip(oEvent)
{
var oDiv=document.getElementById("divTip1");
oDiv.style.visibility="hidden";
}
</script>
</head>
<body>
<p> Move your mouse over the red square</p>
<div id="div1" style="background-color:red; width:200px; height:200px" onmouseover="showTip(event);" onmouseout="hideTip(event)"></div>
<div id="divTip1" style="background-color:Yellow; position:absolute; visibility:hidden; padding:5px">
<span>Here is a tip created by JavaScript and CSS</span>
</div>
</body>
</html>
21 Foldable Area
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script type="text/javascript">
function toggle(sDivId)
{
var oDiv=document.getElementById(sDivId);
oDiv.style.display=(oDiv.style.display=="none")?"block":"none";
}
</script>
</head>
<body>
<div style="background-color:Blue; color:White; font-weight:bold; padding:10px; cursor:pointer" onclick="toggle('div1')">
Click Here.</div>
<div style="border:3px solid blue; height:100px; padding:10px" id="div1">
This is some content to be shown and hidden.
</div>
<p> </p>
<div style="background-color:Blue; color:White; font-weight:bold; padding:10px; cursor:pointer" onclick="toggle('div2')">
Click Here.</div>
<div style="border:3px solid blue; height:100px; padding:10px" id="div2">
This is some content to be shown and hidden.Hi!
</div>
<div></div>
</body>
</html>
22 Deal With Forms
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" src="EventUtil.js"></script>
<script type="text/javascript">
var FormUtil=new Object;
//This function makes sure when the page is loaded for the first time,the first item of the form is focused
FormUtil.focusOnFirst=function(){
if(document.forms.length>0){
for(var i=0;i<document.forms[0].length;i++){
var oField=document.forms[0].elements[i];
if(oField.type!="hidden"){
oField.focus();
return;
}
}
}
};
//By using the maxlength property of a text box,this function helps user to move the focus to next control
FormUtil.autoForward=function(oTextBox){
var oForm=oTextBox.form;
if(oForm.elements[oForm.elements.length-1]!=oTextBox&&oTextBox.value.length==oTextBox.getAttribute("maxlength")){
for(var i=0;i<oForm.elements.length;i++){
if(oForm.elements[i]==oTextBox){
for(var j=i+1;j<oForm.elements.length;j++){
if(oForm.elements[j].type!="hidden"){
oForm.elements[j].focus();
return;
}
}
}
}
}
};
//shows how to get access to the controls in the form
function getValues()
{
var oText=document.getElementById("txtComments");
alert(oText.value+"/n Its length is: "+oText.value.length);
var oListBox=document.getElementById("selAge");
var arrayIndex=ListUtil.getSelectedIndexes(oListBox);
var arrayValues=new Array;
for(var i=0;i<arrayIndex.length;i++)
arrayValues.push(oListBox.options[arrayIndex[i]].value);
alert("You selected: "+arrayValues);
}
//support increase and decrease numbers by keybord
function numericScroll(oTextBox,oEvent){
oEvent=EventUtil.formatEvent(oEvent);
var iValue=oTextBox.value.length==0?0:parseInt(oTextBox.value);
if(oEvent.keyCode==38){
oTextBox.value=iValue+1;
}else if(oEvent.keyCode==40){
oTextBox.value=iValue-1;
}
}
var ListUtil=new Object;
//get all the selected indexes of a listbox
ListUtil.getSelectedIndexes=function(oListbox){
var arrIndex=new Array;
for(var i=0;i<oListbox.options.length;i++)
if(oListbox.options[i].selected)
arrIndex.push(i);
return arrIndex;
}
//add items dynamically
ListUtil.addItem=function(oListBox,sName,sValue){
var oOption=document.createElement("option");
oOption.appendChild(document.createTextNode(sName));
if(sValue)
oOption.setAttribute("value",sValue);
oListBox.appendChild(oOption);
}
//remove items dynamically
ListUtil.remove=function(oListBox,iIndex){
oListBox.remove(iIndex);
}
//move items from one list box to the other
ListUtil.move=function(oListFrom,oListTo,iIndex){
var oOpition=oListFrom.options[iIndex];
if(oOpition!=null)
oListTo.appendChild(oOpition);
}
function addListItem(oListBoxID)
{
var oListBox=document.getElementById(oListBoxID);
var str=window.prompt("Input item name");
ListUtil.addItem(oListBox,str,str);
}
</script>
</head>
<body onload="FormUtil.focusOnFirst()"> <!-- focusOnFirst is used here-->
<form method="post" action="javascript:getValues()" runat="server">
<label for="txtName">Name:</label><br />
<input type="text" name="txtName" onfocus="this.select()" /> <br />
<label for="txtPassword">Password:</label><br />
<input type="password" id="txtPassword" name="txtPassword" /><br />
<label for="autoForwardTextBox">autoForwardTextBox:</label><br />
<input type="text" maxlength="6" name="autoForwardTextBox" id="autoForwardTextBox" onkeyup="FormUtil.autoForward(this)"
onkeydown="numericScroll(this,event)" />
<br />
<label for="selAge">Age:</label><br />
<select name="selAge" id="selAge" multiple="multiple">
<option>18-21</option>
<option>22-25</option>
<option>25-28</option>
<option>28-31</option>
</select><br />
<input type="button" value="More Items..." onclick="addListItem('selAge')"/><br />
<label for="txtComments">Comments:</label><br />
<textarea rows="10" cols="50" id="txtComments" name="txtComments"></textarea><br />
<input type="button" value="Submit Form" onclick="this.disabled=true;this.form.submit();"/>
<input type="reset"value="Reset Values" />
</form>
</body>
</html>
23 XML DOM in IE
The following is the xml file test.xml and its schema
<?xml version="1.0" encoding="UTF-8"?>
<PatientInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Untitled2.xsd">
<Name>Jack</Name>
<Sex>Male</Sex>
<Prescription>
<Medicine>VC</Medicine>
<Amount>12</Amount>
<Medicine>VE</Medicine>
<Amount>234</Amount>
</Prescription>
<Prescription>
<Medicine>VD</Medicine>
<Amount>11</Amount>
</Prescription>
</PatientInfo>
Untitled2.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="PatientInfo">
<xs:complexType>
<xs:sequence>
<xs:element name="Name" type="xs:string"/>
<xs:element name="Sex" type="xs:string"/>
<xs:element name="Prescription" type="Prescription" minOccurs="0" maxOccurs="unbounded"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="Prescription">
<xs:sequence minOccurs="1" maxOccurs="unbounded">
<xs:element name="Medicine" type="xs:string"></xs:element>
<xs:element name="Amount" type="xs:int"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:schema>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script type="text/jscript">
function createXMLDOM()
{
var arrSignature=["MSXML2.DOMDocument.5.0","MSXML2.DOMDocument.4.0","MSXML2.DOMDocument.3.0",
"MSXML2.DOMDocument","Microsoft.XmlDom"];
for (var i=0;i<arrSignature.length;i++)
{
try
{
var oXmlDom=new ActiveXObject(arrSignature[i]);
return oXmlDom;
}
catch(oError)
{
//ignore
}
}
throw new Error("MSXML is not installed on your system");
}
function tryLoadXML()
{
var oXmlDom=createXMLDOM();
oXmlDom.onreadystatechange=function()
{
if(oXmlDom.readyState==4)
alert("Done!");
};
oXmlDom.load("test.xml");
alert(oXmlDom.xml);
}
</script>
</head>
<body onload="tryLoadXML();">
</body>
</html>