A simple example of using javascript to implement a digital verification code

Source: Internet
Author: User

Example:
Copy codeThe Code is as follows:
<! 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>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312"/>
<Title> JS Verification Code </title>
<Style type = "text/css">
. Code
{
Background-image: url(code.jpg );
Font-family: Arial;
Font-style: italic;
Color: Red;
Border: 0;
Padding: 2px 3px;
Letter-spacing: 3px;
Font-weight: bolder;
}
. Unchanged
{
Border: 0;
}
</Style>
<Script language = "javascript" type = "text/javascript">

Var code; // define the verification code globally
Function createCode ()
{
Code = "";
Var codeLength = 4; // The length of the Verification Code
Var checkCode = document. getElementById ("checkCode ");
Var selectChar = new Array (,); // All characters of the verification code that can be composed of candidates.

For (var I = 0; I <codeLength; I ++)
{


Var charIndex = Math. floor (Math. random () * 10 );
Code + = selectChar [charIndex];


}
// Alert (code );
If (checkCode)
{
CheckCode. className = "code ";
CheckCode. value = code;
}

}

Function validate ()
{
Var inputCode = document. getElementById ("input1"). value;
If (inputCode. length <= 0)
{
Alert ("Enter the verification code! ");
}
Else if (inputCode! = Code)
{
Alert ("Incorrect verification code! ");
CreateCode (); // refresh the verification code
}
Else
{
Alert ("OK ");
}

}

</Script>
</Head>
<Body onload = "createCode ()">
<Form action = "#">
<Input type = "text" id = "input1"/>
<Input type = "text" onclick = "createCode ()" readonly = "readonly" id = "checkCode" class = "unchanged" style = "width: 80px "/> <br/>
<Input id = "Button1" onclick = "validate ();" type = "button" value = "OK"/>
</Form>
</Body>
</Html>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.