Checkcode.js
/*
Getcheckcode (ElementID) generates a CAPTCHA that writes HTML image source code to the innerHTML of HTML elements with ID ElementID
Checkcodeok ("User-entered authentication code") returns True, that is, the validation
*/
var Imgfolderpath = "images/checkcode/"; Store path
var fileext = ". gif"; The file name extension, plus the dot
var imgwidth = 15; Image width
var imgheight = 20; High image
var imgfilename = new Array (10); File name, do not add name extension
var checkcodestr = ""; Holds the current authentication code, which can be used to compare
imgfilename[0] = "0";
imgfilename[1] = "1";
imgfilename[2] = "2";
imgfilename[3] = "3";
imgfilename[4] = "4";
imgfilename[5] = "5";
imgfilename[6] = "6";
imgfilename[7] = "7";
imgfilename[8] = "8";
imgfilename[9] = "9";
function Getcheckcode (elementid)//Generate verification code, which will be written to HTML image source in innerHTML of HTML elements with ID ElementID
{
Htmlstr = "";
Checkcodestr = ""; Empty the original verification code
for (i = 0; i < 4; i + +)
{
num = Math.Round (math.random () * 10-0.5);
Checkcodestr + + num.tostring ();
FilePath = Imgfolderpath + imgfilename[num] + fileext;
Htmlstr + + ';
Htmlstr = Htmlstr.replace ("@width @", imgwidth);
Htmlstr = Htmlstr.replace ("@height @", imgheight);
Htmlstr = Htmlstr.replace ("@src @", filePath);
Htmlstr = Htmlstr.replace ("@elementid @", elementid);
}
document.getElementById (elementid). InnerHTML = Htmlstr;
}
function Checkcodeok (str)
{
if (str = CHECKCODESTR)
{
return true;
}
Else
{
return false;
}
}
test.html < script language =javascript src =checkcode.js ></script >
< body onload = "Getcheckcode (' checkcodeimg ')" >
< div id = "Checkcodeimg" > <!--captcha image appears here--> </div >
< input type =button value = "click Me" onclick = "getcheckcode (' checkcodeimg ')" >< br >< br >
< input type =text name = "Checkcode" >
< input type =button value = "Check" onclick = "if (Checkcodeok (document.getElementById (' Checkcode '). Value)" {Alert (' O K ');} else {alert (' Error ')} ' >
</Body >