onchange事件验证文本框格式,不正确光标返回原文本框,这个js怎么写?

现在有个金额 的文本框,要求金额保留两位小数,如果格式不正确,则光标继续返回在这个文本框, 

html代码: 
aaa: 
<input type="text" id="aaa" name="aaa" value="0.00" onchange="checkDecimal(this);"><br></br> 
bbb: 
<input type="text" id="bbb" name="bbb"  value="" ><br></br> 
ccc: 
<input type="text" id="ccc" name="ccc"  value="" ><br></br> 

调用的js: 
/* 
功能:金额保留2位小数 
日期:09:56 2011-6-30 
author: wlj 
*/ 
function checkDecimal(element){
var tmp = element.value.split(".") 
if(!isNaN(element.value)){ 
if(tmp.length!=2||tmp[1].length!=2){
alert("输入金额请保留2位小数!"); 
document.getElementByName("aaa").focus(); 
return false; 


else{ 
alert("输入金额必须是数字类型!"); 
                 document.getElementByName("aaa").focus(); 
return false; 
}

上面红色字体没有作用,当我在aaa文本框内输入:“test”,然后鼠标去点bbb文本框的时候,弹出窗口 提示"输入金额必须是数字类型!",但是光标指向了bbb文本框,而我js里写的 继续停留在aaa文本框 没有实现。 
我要怎样才能使验证格式错误,光标能一直停留在原文本框内呢? 


 

onchange事件不行,需要使用onblur事件 
还有你那个getElementByName好像也不行。以下实例 

<html>  
<head>  
<script type="text/javascript">  
function checkDecimal(element){   
var tmp = element.value.split(".")   
if(!isNaN(element.value)){   
    if(tmp.length!=2||tmp[1].length!=2){   
    document.myForm.aaa.focus();   
    //document.getElementByName("name").focus();  
    alert("输入金额请保留2位小数!");   
    document.getElementById('aaa').value='0.00';   
    return false;  
    }   
}   
else{   
    alert("输入金额必须是数字类型!");    
    document.getElementById('aaa').focus();   
    document.getElementById('aaa').value='0.00';   
    return false;  
    }   
}  
</script>  
</head>  
   
<body >  
<table>  
<form name="myForm">  
aaa:   
<input type="text" id="aaa" name="aaa" value="0.00" onblur="checkDecimal(this);"><br></br>   
bbb:   
<input type="text" id="bbb" name="bbb"  value="" ><br></br>   
ccc:   
<input type="text" id="ccc" name="ccc"  value="" ><br></br>   
  
</form>  
</table>  
  
</body>  
</html>  

 

原文地址:https://www.cnblogs.com/yony/p/2573861.html