Home > Article > Web Front-end > How to implement four-digit random verification code in javascript
Javascript method to implement four-digit random verification code: first create a random number through "function random(max,min){...}"; then create it through "function code(){...}" Random four-digit verification code; finally call the verification code function.
The operating environment of this article: windows7 system, javascript version 1.8.5, DELL G3 computer
How does javascript implement a four-digit random verification code?
JS implements 4-digit random verification code
Write a 4-digit random number that is case-insensitive and contains numbers through random numbers.
CSS style
p{ width: 60px; height: 20px; display: inline-block; letter-spacing: 3px; border: 1px solid red; } #p{ height: 20px; margin-bottom: 10px; } #btn,p:hover{ cursor: default; } button{ display: block; }
Main part
<p id="box"> 验证码 <input type="text" id="int" /> <p id="p"></p> <p id="p"></p> <button id="btn">提交</button> </p>
JS part
//随机数 function random(max,min){ return Math.round(Math.random()*(max-min)+min); } //随机4位验证码 function code(){ //将数字、小写字母及大写字母输入 var str="1234567890qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM"; //给一个空字符串 var res=''; //循环4次,得到4个字符 for(var i=0;i<4;i++){ //将得到的结果给字符串,调用随机函数,0最小数,62表示数字加字母的总数 res+=str[random(0,62)]; } p.innerHTML=res; } code(); //调用验证码函数 p.onclick=code; //点击也可以刷新验证码 //验证验证码 btn.onclick=function(){ var int=document.getElementById("int").value;//获取用户输入的值 var p=document.getElementById("p").innerText;//获取验证码 //判断用户输入与验证码的大写一致(不分大小写) if(int.toUpperCase()==p.toUpperCase()){ p.innerHTML="验证码正确"; }else{ p.innerHTML="验证码错误"; } }
Achievement result
Summary
Math.round(): Rounding
Math.random(): Random number
toUpperCase(): Convert the string to uppercase
Recommended study: "javascript Advanced Tutorial"
The above is the detailed content of How to implement four-digit random verification code in javascript. For more information, please follow other related articles on the PHP Chinese website!