昨天的文章 javascript 输入内容检测(正则表达式方法)里面使用的是弹出窗口警告输入了错误的内容
对于用户体验来说,弹出窗口是一个很不爽的过程,所以今天进行了简单的改写
效果为,当输入错误时,在输入框右边提示错误
html部分:
<div>
<input name="page_num" id="page_num" type="text" class="input" onkeyup="number()"/>
<span style="display:none" id="showPage">请输入数字</span>
<span id="startDateNotice" style="color:red;font-size:10px" ></span>
<input id="cheap_price" name="cheap_price" style="width:158px" type="text" onkeyup="number()">
<span style="display:none;" id="showCheap">请以“39.90”类格式输入价格</span>
<span id="sfeeNotice" style="color:red;font-size:10px" ></span>
</div>
相对于昨天,加上了一个隐藏的<span>
js代码:
1 . 首先获取元素
var Page_num=document.getElementById("page_num");
var cheap_price=document.getElementById("cheap_price");
var showPage=document.getElementById("showPage");
var showCheap=document.getElementById("showCheap");
2. 正则函数:
function Judge(k,m,n){
//k 是被判断的元素
//m是正则表达式,用来判断
//n是警告的显示元素
var patrn=m;
if (patrn.exec(k.value)) {
n.setAttribute("style","display:none;");
return;
} else{
if(k.value==""){
//n.setAttribute("style","display:none;");
return;
}else{
n.setAttribute("style","display:inline;");
n.setAttribute("style","color:red;font-size:10px;");
k.value="";
}
}
}
3. 使用函数
Judge(Page_num,/^\d+$/,showPage);
Judge(cheap_price,/^\d{0,8}\.{0,1}(\d{1,2})?$/,showCheap);
完整代码:
<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>javascript 输入内容检测</title>
<script type="text/javascript">
function number(){
var Page_num=document.getElementById("page_num");
var cheap_price=document.getElementById("cheap_price");
var showPage=document.getElementById("showPage");
var showCheap=document.getElementById("showCheap");
Judge(Page_num,/^\d+$/,showPage);
Judge(cheap_price,/^\d{0,8}\.{0,1}(\d{1,2})?$/,showCheap);
function Judge(k,m,n){
var patrn=m;
if (patrn.exec(k.value)) {
n.setAttribute("style","display:none;");
return;
} else{
if(k.value==""){
//n.setAttribute("style","display:none;");
return;
}else{
n.setAttribute("style","display:inline;");
n.setAttribute("style","color:red;font-size:10px;");
k.value="";
}
}
}
}
</script>
</head>
<body>
<div>
<input name="page_num" id="page_num" type="text" class="input" onkeyup="number()"/>
<span style="display:none" id="showPage">请输入数字</span>
<span id="startDateNotice" style="color:red;font-size:10px" ></span>
<input id="cheap_price" name="cheap_price" style="width:158px" type="text" onkeyup="number()">
<span style="display:none;" id="showCheap">请以“39.90”类格式输入价格</span>
<span id="sfeeNotice" style="color:red;font-size:10px" ></span>
</div>
</body>
</html>