現在有個金額 的文本框,要求金額保留兩位小數,如果格式不正確,則光標繼續返回在這個文本框,
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>