<!DOCTYPE html>
<html>
<head>
<title>前端验证码</title>
<meta charset="utf-8">
</head>
<body>
<!--
readonly="readonly" 设置为只读
onsubmit="yanzheng()" 点击提交时做前端验证
-->
<form action="" method="POST" onsubmit="yanzheng()">
<input type="text" id="yzm" placeholder="请输入验证码">
<input type="text" style="width:50px" readonly="readonly" id="code">
<br>
<input type="submit" value="提交">
</form>
<script type="text/javascript">
var inp1 = document.getElementById('yzm');
var inp2 = document.getElementById('code');
var arr1_value='';
//声明函数
function createcode(){
var arr1 = ['0','1','2','3','4','5','6','7','8','9','A','a','B','b','C','c','D','d'];
for (var i = 1; i<=4; i++){
/*
Math.floor 向下取整
Math.random 获取0-1之间的随机数
*/
var arr1_index = Math.floor(Math.random()*16);
arr1_value += arr1[arr1_index];
}
inp2.value=arr1_value;
}
//调用函数
createcode();
function yanzheng(){
if (inp1.value == inp2.value) {
alert('验证成功');
}else{
alert('验证失败');
}
}
</script>
</body>
</html>