js basic functions

1. Array API of javascript:

//Defined array 
var pageIds = new Array(); 
pageIds.push('A'); 
//Array length 
pageIds.length; 
//shift: Delete the first item of the original array and return the value of the deleted element; if the array is empty, return undefined 
var a = [1,2,3,4,5]; 
var b = a.shift(); //a: [2,3,4,5] b: 1 
//unshift: Add the parameter to the beginning of the original array and return the length of the array 
var a = [1,2,3,4,5]; 
var b = a.unshift(-2,-1); //a: [-2,-1,1,2,3,4,5] b: 7 
//Note: in IE6.0 The return value of the next test is always undefined,FF2.0 The return value of the next test is 7, so the return value of this method is unreliable and can be used when the return value is needed splice Instead of this method. 
//pop: Delete the last item of the original array and return the value of the deleted element; if the array is empty, return undefined 
var a = [1,2,3,4,5]; 
var b = a.pop(); //a: [1,2,3,4] b: 5 
//push: Add the parameter to the end of the original array and return the length of the array 
var a = [1,2,3,4,5]; 
var b = a.push(6,7); //a: [1,2,3,4,5,6,7] b: 7 
//concat: Returns a new array composed of adding parameters to the original array 
var a = [1,2,3,4,5]; 
var b = a.concat(6,7); //a: [1,2,3,4,5] b: [1,2,3,4,5,6,7] 
//splice(start,deleteCount,val1,val2,): from start Location start delete deleteCount Item and insert from this location val1,val2, 
var a = [1,2,3,4,5]; 
var b = a.splice(2,2,7,8,9); //a: [1,2,7,8,9,5] b: [3,4] 
var b = a.splice(0,1); //with shift 
a.splice(0,0,-2,-1); var b = a.length; //with unshift 
var b = a.splice(a.length-1,1); //with pop 
a.splice(a.length,0,6,7); var b = a.length; //with push 
//reverse: Reverse array 
var a = [1,2,3,4,5]; 
var b = a.reverse(); //a: [5,4,3,2,1] b: [5,4,3,2,1] 
//sort(orderfunction): Sorts the array by the specified parameters 
var a = [1,2,3,4,5]; 
var b = a.sort(); //a: [1,2,3,4,5] b: [1,2,3,4,5] 
//slice(start,end): Returns a new array of items from the specified start subscript to the end subscript in the original array 
var a = [1,2,3,4,5]; 
var b = a.slice(2,5); //a: [1,2,3,4,5] b: [3,4,5] 
//join(separator): Group the elements of an array into a string to separator Is the separator, if omitted, comma is used as the separator by default 
var a = [1,2,3,4,5]; 
var b = a.join("|"); //a: [1,2,3,4,5] b: "1|2|3|4|5" 

2.dom most commonly used API:

//document Method: 
getElementById(id) Node Returns a reference to a specified node 
getElementsByTagName(name) NodeList Returns a collection of all matching elements in a document 
createElement(name) Node Node 
createTextNode(text) Node Create a plain text node 
ownerDocument Document Point to the document to which this node belongs 
documentElement Node Return html node 
document.body Node Return body node 
//element Method: 
getAttribute(attributeName) String Returns the value of the specified property 
setAttribute(attributeName,value) String Assign a value to a property 
removeAttribute(attributeName) String Remove the specified property and its value 
getElementsByTagName(name) NodeList Returns the set of all matching elements in a node 
//node Method: 
appendChild(child) Node Add a new child node to the specified node 
removeChild(child) Node Remove the child of the specified node 
replaceChild(newChild,oldChild) Node Replace the child of the specified node 
insertBefore(newChild,refChild) Node Insert a new node in front of the node at the same level 
hasChildNodes() Boolean Return if the node has children true 
//node Properties: 
nodeName String Store the name of the node as a string 
nodeType String Store node types in integer data format 
nodeValue String Store node values in the available format 
parentNode Node Reference to the parent of the node 
childNodes NodeList Set of references to child nodes 
firstChild Node Reference to the first child node in the combination of child nodes 
lastChild Node Reference to the last child node in the combination of child nodes 
previousSibling Node Point to the previous sibling node; if this node is a sibling node, the value is null 
nextSibling Node Point to the next sibling node; if this node is a sibling node, the value is null

3. A map object searched online:

function HashMap() 
{ 
/** Map Size **/ 
var size = 0; 
/** Object **/ 
var entry = new Object(); 
/** Save **/ 
this.put = function (key , value) 
{ 
if(!this.containsKey(key)) 
{ 
size    ; 
} 
entry[key] = value; 
} 
/** Take **/ 
this.get = function (key) 
{ 
return this.containsKey(key) ? entry[key] : null; 
} 
/** Delete **/ 
this.remove = function ( key ) 
{ 
if( this.containsKey(key) && ( delete entry[key] ) ) 
{ 
size --; 
} 
} 
/** Include Key or not**/ 
this.containsKey = function ( key ) 
{ 
return (key in entry); 
} 
/** Include Value or not**/ 
this.containsValue = function ( value ) 
{ 
for(var prop in entry) 
{ 
if(entry[prop] == value) 
{ 
return true; 
} 
} 
return false; 
} 
/** All values**/ 
this.values = function () 
{ 
var values = new Array(); 
for(var prop in entry) 
{ 
values.push(entry[prop]); 
} 
return values; 
} 
/** All Key **/ 
this.keys = function () 
{ 
var keys = new Array(); 
for(var prop in entry) 
{ 
keys.push(prop); 
} 
return keys; 

} 
/** Map Size **/ 
this.size = function () 
{ 
return size; 
} 
/* empty */ 
this.clear = function () 
{ 
size = 0; 
entry = new Object(); 
} 
} 
var map = new HashMap(); 
/* 
map.put("A","1"); 
map.put("B","2"); 
map.put("A","5"); 
map.put("C","3"); 
map.put("A","4"); 
*/ 
/* 
alert(map.containsKey("XX")); 
alert(map.size()); 
alert(map.get("A")); 
alert(map.get("XX")); 
map.remove("A"); 
alert(map.size()); 
alert(map.get("A")); 
*/ 
/** At the same time, the object can also be used as a Key**/ 
/* 
var arrayKey = new Array("1","2","3","4"); 
var arrayValue = new Array("A","B","C","D"); 
map.put(arrayKey,arrayValue); 
var value = map.get(arrayKey); 
for(var i = 0 ; i < value.length ; i  ) 
{ 
//alert(value[i]); 
} 
*/ 
/** When an object is used as a Key, the toString() method of the object is called automatically. In fact, the String object is still the Key**/ 
/** If it's a custom object, you have to override the toString() method. Otherwise, it's the following result**/ 
function MyObject(name) 
{ 
this.name = name; 
} 
/** 
function MyObject(name) 
{ 
this.name = name; 
this.toString = function () 
{ 
return this.name; 
} 
} 
**/ 
var object1 = new MyObject("Xiao Zhang"); 
var object2 = new MyObject("Pet name"); 
map.put(object1,"Xiao Zhang"); 
map.put(object2,"Pet name"); 
alert(map.get(object1)); 
alert(map.get(object2)); 
map.remove("xxxxx"); 
alert(map.size()); 
/** Running result small name small name size = 1**/ 
/** If you copy the object of toString() method instead, the effect will be totally different**/ 

4. Common digital functions:

//·Digital type(Number) 
//1.statement 
var i = 1; 
var i = new Number(1); 
//2.Conversion between string and number 
var i = 1; 
var str = i.toString(); //Result: "1" 
var str = new String(i); //Result: "1" 
i = parseInt(str); //Result: 1 
i = parseFloat(str); //Result: 1.0 
//Be careful: parseInt,parseFloat It's like"32G"String,Cast to 32 
//3.Judge whether it is a valid number 
var i = 123; var str = "string"; 
if( typeof i == "number" ){ } //true 
//Some methods(as:parseInt,parseFloat)A special value will be returned NaN(Not a Number) 
//Please note in point 2[Be careful],This method is not suitable for judging whether a string is numeric or not!! 
i = parseInt(str); 
if( isNaN(i) ){ } 
//4.Digital comparison 
//This knowledge and[string comparison]identical 
///5.Decimal to integer 
var f = 1.5; 
var i = Math.round(f); //Result:2 (Rounding) 
var i = Math.ceil(f); //Result:2 (Return greater than f Minimum integer of) 
var i = Math.floor(f); //Result:1 (Return less than f Maximum integer for) 
//6.Format display number 
var i = 3.14159; 
//Floating point numbers formatted as two decimal places 
var str = i.toFixed(2); //Result: "3.14" 
//Floating point numbers formatted as five digits(Five digits from left to right,Not enough to fill zero) 
var str = i.toPrecision(5); //Result: "3.1415" 
//7.X Conversion of decimal digits 
//Not very well. -.- 
var i = parseInt("0x1f",16); 
var i = parseInt(i,10); 
var i = parseInt("11010011",2); 
//8.random number 
//Return to 0-1 Any decimal between 
var rnd = Math.random(); 
//Return to 0-n Any integer between(Barring n) 
var rnd = Math.floor(Math.random() * n) 

5. js stack searched online:

function stack(){ 
if(this.top==undefined){ 
//Initializes the top pointer and data storage area of the stack 
this.top=0; 
this.unit=new Array(); 
} 
this.push=function(pushvalue){ 
//Define how to push into the stack 
this.unit[this.top]=pushvalue; 
this.top =1; 
} 
this.readAllElements=function(){ 
//Define how to read all data 
if(this.top==0){ 
alert("The current stack is empty, unable to read data"); 
return(""); 
} 
var count=0; 
var outStr=""; 
for(count=0;count<this.top;count  ){ 
outStr =this.unit[count] ","; 
} 
return(outStr); 
} 
this.pop=function(){ 
//How to define a pop-up stack 
if(this.top==0){ 
alert("The current stack is empty, unable to pop up data"); 
return(""); 
} 
var popTo=this.unit[this.top-1]; 
this.top--; 
return(popTo); 
/* Pop the data from the stack and decrease the top pointer by one, but the resource is not released here 
That is to say, the data still exists in the array of this.unit, but it can't be accessed. at present 
I didn't think of a good solution.*/ 
} 
} 

6. The most commonly used JavaScript date function:

//·Date type(Date) 
//1.statement 
var myDate = new Date(); //System current time 
var myDate = new Date(yyyy, mm, dd, hh, mm, ss); 
var myDate = new Date(yyyy, mm, dd); 
var myDate = new Date("monthName dd, yyyy hh:mm:ss"); 
var myDate = new Date("monthName dd, yyyy"); 
var myDate = new Date(epochMilliseconds); 
//2.Get a part of time 
var myDate = new Date(); 
myDate.getYear(); //Get current year(2 position) 
myDate.getFullYear(); //Get full year(4 position,1970-????) 
myDate.getMonth(); //Get current month(0-11,0 On behalf of January) 
myDate.getDate(); //Get current day(1-31) 
myDate.getDay(); //Get current week X(0-6,0 For Sunday) 
myDate.getTime(); //Get current time(From 1970.1.1 Milliseconds to start) Time stamp!! 
myDate.getHours(); //Get current hours(0-23) 
myDate.getMinutes(); //Get current minutes(0-59) 
myDate.getSeconds(); //Get current seconds(0-59) 
myDate.getMilliseconds(); //Get current milliseconds(0-999) 
myDate.toLocaleDateString(); //Get current date 
myDate.toLocaleTimeString(); //Get current time 
myDate.toLocaleString( ); //Get date and time 
//3.Time before or in the future 
var myDate = new Date(); 
myDate.setDate(myDate.getDate()   10); //Current time plus 10 days 
//Similar methods are basically the same,with set Start,Refer to point 2 for details 
//4.Calculate the offset of two dates 
var i = daysBetween(beginDate,endDate); //Return days 
var i = beginDate.getTimezoneOffset(endDate); //Return minutes 
//5.Inspection effective date 
//checkDate() Only allow"mm-dd-yyyy"or"mm/dd/yyyy"Date in two formats 
if( checkDate("2006-01-01") ){ } 
//regular expression (Self written inspection yyyy-mm-dd, yy-mm-dd, yyyy/mm/dd, yy/mm/dd Four kinds) 
var r = /^(\d{2}|\d{4})[\/-]\d{1,2}[\/-]\d{1,2}$/; 
if( r.test( myString ) ){ } 

7. Most commonly used string function API:

//·Character string(String) 
//1.statement 
var myString = new String("Every good boy does fine."); 
var myString = "Every good boy does fine."; 
//2.String connection 
var myString = "Every "   "good boy "   "does fine."; 
var myString = "Every "; myString  = "good boy does fine."; 
//3.Intercept string 
//Intercept the character from the 6th digit 
var myString = "Every good boy does fine."; 
var section = myString.substring(6); //Result: "good boy does fine." 
//Intercept the characters from the beginning of bit 0 to the end of bit 10 
var myString = "Every good boy does fine."; 
var section = myString.substring(0,10); //Result: "Every good" 
//Intercept characters from 11th to 6th 
var myString = "Every good boy does fine."; 
var section = myString.slice(11,-6); //Result: "boy does" 
//Intercept 4 characters from bit 6 
var myString = "Every good boy does fine."; 
var section = myString.substr(6,4); //Result: "good" 
//4.Convert case 
var myString = "Hello"; 
var lcString = myString.toLowerCase(); //Result: "hello" 
var ucString = myString.toUpperCase(); //Result: "HELLO" 
//5.string comparison 
var aString = "Hello!"; 
var bString = new String("Hello!"); 
if( aString == "Hello!" ){ } //Result: true 
if( aString == bString ){ } //Result: true 
if( aString === bString ){ } //Result: false (Two objects are different,Even though they have the same value) 
//6.Retrieve string 
var myString = "hello everybody."; 
// If it cannot be retrieved, it will return-1,Retrieved words return the starting position in the string 
if( myString.indexOf("every") > -1 ){ } //Result: true 
////7. Find replacement string 
var myString = "I is your father."; 
var result = myString.replace("is","am"); //Result: "I am your father." 
//8.Special characters: 
//\b : Backward character \t : Horizontal tab 
//\n : Newline character \v : vertical tab  
//\f : Page break \r : Carriage return character 
//\" : Double quotation marks \' : Single quotation mark 
//\\ : Anti inclined rod 
//9.Convert characters to Unicode Code 
var myString = "hello"; 
var code = myString.charCodeAt(3); //Return"l"Of Unicode Code(integer) 
var char = String.fromCharCode(66); //Return Unicode Character 66 
//10.Convert string to URL Code 
var myString = "hello all"; 
var code = encodeURI(myString); //Result: "hello all" 
var str = decodeURI(code); //Result: "hello all" 
//There are also: encodeURIComponent() decodeURIComponent() 

8. Mathematical function:

Math object 
1. Math.abs(num): returns the absolute value of num 
2. Math.acos(num): returns the arccosine of num 
3. Math.asin(num): returns the arcsine value of num 
4. Math.atan(num): returns the arctangent of num 
5. Math.atan2(y,x): returns the arctangent of the quotient of Y divided by X 
6. Math.ceil(num): returns the minimum integer greater than num 
7. Math.cos(num): returns the cosine value of num 
8. Math.exp(x): returns the number based on the natural number and the power of X 
9. Math.floor(num): returns the maximum integer less than num 
10.Math.log(num): returns the natural logarithm of num 
11.Math.max(num1,num2): returns the larger of num1 and num2 
12.Math.min(num1,num2): returns the smaller of num1 and num2 
13.Math.pow(x,y): returns the value of X to the power of Y 
14.Math.random(): returns a random number between 0 and 1 
15.Math.round(num): returns the value of num after rounding 
16.Math.sin(num): returns the sine value of num 
17.Math.sqrt(num): returns the square root of num 
18.Math.tan(num): returns the tangent value of num 
19.Math.E: natural number (2.718281828459045) 
20. Math.ln2: natural logarithm of 2 (0.6931471805599453) 
21. Math.ln10: natural logarithm of 10 (2.302585092994046) 
22. Math.log2e: log 2 is the bottom natural number (1.4426950408889634) 
23. Math.log10e: log 10 is the bottom natural number (0.4342944819032518) 
24.Math.PI : π(3.141592653589793) 
25. Math.sqrt1_: square root of 1 / 2 (0.7071067811865476) 
26. Math.sqrt2: square root of 2 (1.4142135623730951) 

9. Browser feature function:

//1.Browser name 
//IE : "Microsoft Internet Explorer" 
//NS : "Netscape" 
var browserName = navigator.appName; 
//2.Browser version 
var browserVersion = navigator.appVersion; 
//3.Client operating system 
var isWin = ( navigator.userAgent.indexOf("Win") != -1 ); 
var isMac = ( navigator.userAgent.indexOf("Mac") != -1 ); 
var isUnix = ( navigator.userAgent.indexOf("X11") != -1 ); 
//4.Judge whether an object is supported,Method,attribute 
//When an object,Method,Property undefined returns undefined or null etc.,These special values are false 
if( document.images ){ } 
if( document.getElementById ){ } 
//5.Check browser current language 
if( navigator.userLanguage ){ var l = navigator.userLanguage.toUpperCase(); } 
//6.Check whether the browser supports Cookies 
if( navigator.cookieEnabled ){ } 

10.JavaScript object-oriented method implementation inheritance: call method

// Animals animal 
function animal(bSex){ 
this.sex = bSex 
this.getSex = function(){ 
return this.sex 
} 
} 
// Class static variable (If you don't change it~~) 
animal.SEX_G = new Object(); // female 
animal.SEX_B = new Object(); // male 
// Subspecies of animals 
function bird(bSex){ 
animal.call(this, bSex); 
this.fly = function(iSpeed){ 
alert("Up to speed per hour "   iSpeed); 
} 
} 
// Zoon fish 
function fish(bSex){ 
animal.call(this, bSex); 
this.swim = function(iSpeed){ 
alert("Swimming speed up to "   iSpeed) 
} 
} 
// Fish and bird hybrids... 
function crossBF(bSex){ 
bird.call(this, bSex); 
fish.call(this, bSex); 
} 
var oPet = new crossBF(animal.SEX_G); // Female fish and bird 
alert(oPet.getSex() == animal.SEX_G ? "female" : "male"); 
oPet.fly(124) 
oPet.swim(254) 

11. Write JavaScript in object-oriented programming mode:

MyTool = new function(){ 
/** 
* Returns a non empty string, or a default string if there is one 
*/ 
this.notNull = function(str,defaultStr){ 
if(typeof(str)=="undefined"||str==null||str==''){ 
if(defaultStr) 
return defaultStr; 
else 
return ''; 
} 
else{ 
return str; 
} 
} 
} 
rootId = MyTool.notNull(rootId,'001000'); 

12. Common js methods, including some methods of form verification, common methods of pull-down menu, etc

/** 
* Convert JSON objects to strings 
* @param {json Object} json 
* @return {json String} 
*/ 
function jsonObj2Str(json) { 
var str = "{"; 
for (prop in json) { 
str  = prop   ":"   json[prop]   ","; 
} 
str = str.substr(0, str.length - 1); 
str  = "}"; 
return str; 
} 
/** 
* Converts a json string to a json object 
* @param {json String} jsonstr 
* @return {json Object} 
*/ 
function jsonStr2Obj(jsonstr) { 
return eval("(" jsonstr ")"); 
} 
/** 
* Get the left coordinate value of an element 
* @param {dom Object} obj 
* @return {Location value} 
*/ 
function getLeft(obj){ 
var offset=e.offsetLeft; 
if(e.offsetParent!=null) offset =getLeft(e.offsetParent); 
return offset; 
} 
/** 
* Get the top coordinate value of the absolute position of an element 
* @param {dom Object} obj 
* @return {Location value} 
*/ 
function getTop(obj){ 
var offset=e.offsetTop; 
if(e.offsetParent!=null) offset =getTop(e.offsetParent); 
return offset; 
} 
/** 
* Remove the left and right spaces of a string 
* @param {Original string} str 
* @return {Delete string after space} 
*/ 
function trim(str) 
{ 
return str.replace(/(^\s*)|(\s*$)/g,""); 
} 
/** 
* Take an element according to its id 
* @param {Element id value} str 
* @return {dom Object} 
*/ 
function $(str) { 
return document.getElementById(str); 
} 
/** 
* Get an object by name 
* @param {Element name value} str 
* @return {First object returned by name} 
*/ 
function $byName(str) { 
var arr = document.getElementsByName(str); 
if (arr) 
return arr[0]; 
else 
return null; 
} 
/***************The following methods are related to form validation*************************************************/ 
/** 
* Returns a non empty string, or a default string if there is one 
* @param {Original string to convert} str 
* @param {Default} defaultStr 
* @return {Return results} 
*/ 
function notNull(str, defaultStr) { 
if (typeof(str) == "undefined" || str == null || str == '') { 
if (defaultStr) 
return defaultStr; 
else 
return ''; 
} else { 
return str; 
} 
} 
/** 
* Compare two date sizes 
* @param {Text box id} smallDate for smaller date 
* @param {Text box id} bigDate for larger date 
* @param {Error message} msg 
*/ 
function compareTwoDate(smallDate, bigDate, msg) { 
var v1 = $(smallDate).value; 
var v2 = $(bigDate).value; 
if (v1 >= v2) { 
alert(msg); 
v2.focus(); 
return false; 
} 
return true; 
} 
/** 
* A method of comparing two amounts 
* @param {Smaller amount} smallNum 
* @param {Large amount} bigNum 
* @param {Error message} msg 
* @return {Boolean} 
*/ 
function compareTwoNum(smallNum, bigNum, msg) { 
var v1 = $(smallNum).value; 
var v2 = $(bigNum).value; 
if (parseFloat(v1) >= parseFloat(v2)) { 
alert(msg); 
v2.focus(); 
return false; 
} 
return true; 
} 
/** 
* Check if the length of the text box exceeds the specified length 
* @param {Textid} textid 
* @param {Maximum length of text box} len 
* @param {Text box description content} msg 
* @return {If there is an error, return false, otherwise return true} 
*/ 
function checkLength(textId, len, msg) { 
obj = $(textId); 
str = obj.value; 
str = str.replace(/[^\x00-\xff]/g, "**"); 
realLen = str.length; 
if (realLen > len) { 
alert("["   msg   "]"   "Maximum length is"   len   "position,"   "Please re-enter!\n Note: a Chinese character occupies 2 digits."); 
obj.focus(); 
return false; 
} else 
return true; 
} 
/** 
* Judge that a text box cannot be empty 
* @param {Textbox id} textId 
* @param {Text box description content} msg 
* @return {If there is an error, return false, otherwise return true} 
*/ 
function checkIfEmpty(textId, msg) { 
var textObj = $(textId); 
var textValue = textObj.value; 
if (trim(textValue) == '') { 
alert('['   msg   ']Cannot be empty!'); 
textObj.focus(); 
return false; 
} else { 
return true; 
} 
} 
/** 
* Judge that the content of the specified text box must be mail 
* @param {Textbox id} textId 
* @param {Text box description} msg 
* @return {Return true if it is the message content or false} 
*/ 
function checkIsMail(textId, msg) { 
var obj = $(textId); 
if (!_isEmail(obj.value)) { 
alert('['   msg   ']Not a legal email address!'); 
obj.focus(); 
return false; 
} else 
return true; 
} 
/** 
* Verify if it is a message 
* @param {String to verify} strEmail 
* @return {Boolean} 
*/ 
function _isEmail(strEmail) { 
//The next step is to verify that there are more than two'.'No, some words are wrong! 
var first = strEmail.indexOf('.'); 
if (strEmail.indexOf('@')== -1) { 
return false; 
} 
var tempStr = strEmail.substring(first   1); 
if (tempStr.indexOf('.') != -1) { 
return false; 
} 
if (strEmail 
.search(/^\w ((-\w )|(\.\w ))*\@[A-Za-z0-9] ((\.|-)[A-Za-z0-9] )*\.[A-Za-z0-9] $/) != -1) { 
return true; 
} else 
return false; 
} 
/** 
* Determines whether a text box is numeric 
* @param {Textbox id} textId 
* @param {Text box description content} msg 
* @return {Boolean} 
*/ 
function checkIsNum(textId, msg) { 
obj = $(textId); 
if (isNaN(obj.value)) { 
alert('['   msg   ']Must be a number.'); 
obj.focus(); 
return false; 
} else 
return true; 
} 
/** 
* Determine whether a text box contains illegal characters 
* @param {id} textId of text box 
* @param {Text box description content} msg 
* @return {Return false if there is an error, otherwise return true} 
*/ 
function checkIsValid(textId, msg) { 
obj = $(textId); 
if (!_isValidString(obj.value, '['   msg   ']Must not contain illegal characters.')) { 
obj.focus(); 
return false; 
} 
return true; 
} 
/** 
* Determine whether it is a legal string 
* @param {String to be judged} szStr 
* @param {Text description} errMsg 
* @return {If it is legal, return true; otherwise, return false} 
*/ 
function _isValidString(szStr,errMsg) { 
voidChar = "'\"><`~!@#$%^&\(\)()!¥......??""''*"; 
for (var i = 0; i < voidChar.length; i  ) { 
aChar = voidChar.substring(i, i   1); 
if (szStr.indexOf(aChar) > -1){ 
alert(errMsg) 
return false; 
} 
} 
return true; 
} 
/*************** The following methods are related to the pull-down menu*************************************************/ 
/** 
* The control drop-down menu cannot be - 1 (case value = - 1 is not selected) 
* @param {Drop down menu id} selectId 
* @param {Drop down menu description content} msg 
* @param {The value corresponding to the null value of the drop-down menu, which is - 1} nullValue by default 
* @return {Boolean} 
*/ 
function checkChooseSelect(selectId, msg ,nullValue) { 
var obj = $(selectId); 
if (obj.value == notNull(nullValue,'-1')) { 
alert('['   msg   ']Mandatory!'); 
obj.focus(); 
return false; 
} else 
return true; 
} 
/** 
* Get the text for the drop-down menu display 
* @param {Drop down menu dom object} selectObj 
* @return {Returns the displayed "text"} of the drop-down menu 
*/ 
function getSelectText(selectObj) { 
return selectObj.options[selectObj.selectedIndex].text; 
} 
/** 
* Gets the displayed value of the drop-down menu 
* @param {Drop down menu dom object} selectObj 
* @return {Get the displayed "value"} of the drop-down menu 
*/ 
function getSelectValue(selectObj) { 
return selectObj.options[selectObj.selectedIndex].value; 
} 
/** 
* Sets the selection status of the drop-down menu to the specified value 
* @param {Drop down menu object} obj 
* @param {Value to select} value 
*/ 
function setSelectValue(obj, value) { 
/*for (i = obj.options.length - 1; i >= 0; i--) { 
if (obj.options[i].value == value) { 
obj.options[i].selected = true; 
return; 
} 
} 
*/ 
obj.value= value; 
} 
/** 
* Dynamic assembly of pull-down menu according to the content of key value string 
* @param {dom object} obj for pull-down menu assembly 
* @param {Key value pair, and; split, such as' 1, male; 2, female; 3, unknown '} valAndText 
*/ 
function setSelectContent(obj,valAndText){ 
if(trim(valAndText)==''){ 
alert('No data to assemble the pull-down menu!'); 
return false; 
} 
clearSelect(obj); 
var keyandvalues = valAndText.split(';'); 
for(var i=0;i<keyandvalues.length;i  ){ 
var arr = keyandvalues[i].split(','); 
if(arr){ 
var value =arr[0]; 
var text =arr[1]; 
var objOption = new Option(text,value); 
obj.add(objOption); 
} 
} 
} 
/** 
* Clear the contents of the drop-down menu 
* @param {Drop down menu object} obj 
*/ 
function clearSelect(obj) { 
for (var i=obj.options.length; i >0; i--) { 
obj.remove(0); 
} 
} 
/*************** The following methods are related to multiple boxes*************************************************/ 
/** 
* Returns the string composed of the id of the selected checks, separated by commas 
* @param {checks Array} checks 
* @return String of selected IDS 
*/ 
function getCheckedIds(checks){ 
var selectedValue = ''; 
var len = checks.length; 
for(var index=0; index<len; index  ) { 
if(checks[index].checked==true) { 
selectedValue  = checks[index].value ","; 
} 
} 
if(selectedValue.length>0) 
return selectedValue.substring(0,selectedValue.length-1); 
return selectedValue; 
} 


Put the following code into the html tag, and call the above js in the head:

<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--<<<<<<<<<<<Call the above js>>>>>>>>>-->
</HEAD>
<SCRIPT LANGUAGE="JavaScript"> 
<!-- 
/** 
* Example js method of form validation 
*/ 
function check(){ 
if(checkIfEmpty('a','Non empty calibration') 
&&checkIsMail('b','Mailbox check') 
&&checkIsNum('c','Digital check') 
&&checkIsValid('d','Validity verification') 
&&compareTwoDate('e','f','Wrong relationship between small date and large date!') 
&&checkLength('g',5,'Length check') 
&&checkChooseSelect('h','Drop down menu is not empty','-1') 
&&compareTwoNum('k','l','Incorrect size number relationship!')){ 
alert('Calibration pass!'); 
return true; 
}else{ 
return false; 
} 
} 
/** 
* Take the value of the pull-down menu and the text of the sample js method 
*/ 
function getSelect(){ 
var sss = $('h'); 
alert('The text selected by the drop-down menu is:' getSelectText(sss) '\n' 
 'The value selected from the drop-down menu is:' getSelectValue(sss)); 
} 
/** 
* Set the display content of the pull-down menu according to the key value string 
*/ 
function setSelect(){ 
var sss = $('i').value; 
setSelectContent($('h'),sss); 
} 
/** 
* Returns the string of id for the selection status of the multiple selection box array, separated by commas 
*/ 
function getMulti(){ 
alert('Multiple choice id yes:' getCheckedIds(document.getElementsByName('j'))); 
} 
//--> 
</SCRIPT>
<BODY>
<table>
  <tr>
    <td> Not empty:
      <input id='a'></td>
    <td> checkIfEmpty('a','Non empty calibration') </td>
  </tr>
  <tr>
    <td> mailbox:
      <input id='b' value='323232@2323.com'></td>
    <td> checkIsMail('b','Mailbox check') </td>
  </tr>
  <tr>
    <td> number:
      <input id='c' value='aaaa'></td>
    <td> checkIsNum('c','Digital check') </td>
  </tr>
  <tr>
    <td> Legal character:
      <input id='d' value='@$@$#$#!%%#'></td>
    <td> checkIsValid('d','Validity verification') </td>
  </tr>
  <tr>
    <td> Small date:
      <input id='e' value='2010-1-1'>
      //Big date:
      <input id='f' value='2011-1-1'></td>
    <td> compareTwoDate('e','f','Wrong relationship between small date and large date!') </td>
  </tr>
  <tr>
    <td> Small number:
      <input id='k' value='12.3'>
      //Large number:
      <input id='l' value='4564'></td>
    <td> compareTwoNum('k','l','Incorrect size number relationship!') </td>
  </tr>
  <tr>
    <td> Character length verification(<5):
      <input id='g'></td>
    <td> checkLength('g',5,'Length check') </td>
  </tr>
  <tr>
    <td> Non empty verification of pull-down menu:
      <select id='h'>
        <option value='-1'> Please choose </option>
        <option value='1'> Project approval </option>
        <option value='2'> Feasibility study </option>
      </select></td>
    <td> checkChooseSelect('h','Drop down menu is not empty','-1') </td>
  </tr>
  <tr>
    <td colspan='2'><button onclick='check()'> Test form verification method </button></td>
  </tr>
  <tr>
    <td><button onclick='getSelect()'> Get the value of the drop-down menu </button></td>
    <td> getSelectText(sss)and getSelectValue(sss) </td>
  </tr>
  <tr>
    <td> Enter the key value string for the drop-down menu(As shown in the right)
      <input id='i' value='1,male;2,female;3,Unknown'>
      <button onclick='setSelect()'> Set the value of the drop-down menu </button></td>
    <td> setSelectContent($('h'),sss) </td>
  </tr>
  <tr>
    <td><input type='checkbox' name='j' value='aaa1'>
      <input type='checkbox' name='j' value='aaa2'>
      <input type='checkbox' name='j' value='aaa3'>
      <input type='checkbox' name='j' value='aaa4'>
      <button onclick='getMulti()'> Get multiple choices id </button></td>
    <td> getCheckedIds(document.getElementsByName('j')) </td>
  </tr>
</table>
</BODY>


ok, it's done.........

 

Published 0 original articles · praised 2 · visited 8231
Private letter follow

Tags: JSON Javascript less IE

Posted on Tue, 14 Jan 2020 02:36:24 -0500 by metrostars