日期:2014-05-17  浏览次数:20954 次

如何利用javascript强制输入正数(包含小数)
如何利用javascript强制输入正数(包含小数)

------解决方案--------------------
<body>
<script language= "JavaScript ">
function check(str)
{
var pattern = /^\d+(\.\d+)?$/i;
if (pattern.test(str))
alert( "输入正确 ");
else
alert( "错误 ")
}
</script>
<input type= "text " id= "txt " value= " ">
<input type= "button " onclick= "check(txt.value) " value= "Check ">
</body>
------解决方案--------------------
<input type=text id=tst onblur=testNum( 'tst ')>

<script>
function testNum(id){
var obj=document.getElementById(id);
var vnum=obj.value;
if (vnum*1!=vnum){
alert( '您输入的不是数值! ');
obj.focus();
return;
}
if (vnum*1 <=0){
alert( '您输入的是负数! ')
obj.focus();
return;
}
}
</script>
------解决方案--------------------
<script language=javascript>
function onlyNum(){
var keycode = event.keyCode;
var realkey = String.fromCharCode(keycode);
if(keycode==8 || keycode==46|| (keycode> =35 && keycode <=40))return;
else if(!/\d/.test(realkey))event.returnValue = false;
}
</script>

<input onkeydown= "onlyNum(); ">

可以实现但是还是不严谨,.可以输入很多个。你还要加 ". "的个数大于1就返回假才行。