你的位置: Kiyo'Space首页 JavaScript/Jscript 阅读文章 欢迎留下您的足迹

JS textbox 只允许输入数字

[ JavaScript/Jscript ] 分享

OnKeyUp="this.value=this.value.replace(/\D/g,”)"    onpaste="this.value=this.value.replace(/\D/g,”)"

 

 

 

 

 

 

给个代码段:
<input type="text" name="test"
value=""
onkeypress = "return reginput(this, /^\d{0,10}\.?\d{0,2}$/, string.fromcharcode(window.event.keycode))"
onpaste = "return reginput(this, /^\d{0,10}\.?\d{0,2}$/, window.clipboarddata.getdata(text))"
ondrop = "return reginput(this, /^\d{0,10}\.?\d{0,2}$/, window.event.datatransfer.getdata(text))"
>

function reginput(obj, reg, inputstr)
{
if(event.srcelement.getattribute("readonly")||event.srcelement.getattribute("disabled"))return false;
if(event.keycode<46 || event.keycode>57)return false;
var docsel = document.selection.createrange();
if (docsel.parentelement().tagname != "input") return false;
osel = docsel.duplicate()
osel.text = ""
var srcrange = obj.createtextrange()
osel.setendpoint("starttostart", srcrange)
var str = osel.text + inputstr + srcrange.text.substr(osel.text.length)
return reg.test(str)
}

先做一个定长的文本框,
<form name="myform">
<input name="me" maxlength="20" onchange="inputdata()">
</form>
定义函数:
<script language="javascript">
function inputdata()
{
with(window.myform)
{

if(me.value.charat(me.value.length-1)<0|me.value.charat(me.value.length-1)>9)
me.value=me.value.substring(0,me.value.length);
}
}
</script>

发表者:hozi

<script language="javascript">
function key(){
if ((window.event.keycode=="46")||(window.event.keycode>="48"&&window.event.keycode<="57")){
return;
}
else
{
window.event.keycode = 0;
}
}
</script>

<input onkeypress=key() type="text" name="t011" value="" maxlength="5">

只能输入数字和小数点,长度为5。如果不想输入小数点把window.event.keycode=="46"去掉。

发表者:zhao_sh

给文本框加一个maxlength属性就行,如下所示(当然你得用代码生成):
<input type="text" value="ddd" name="txtname" maxlength="3">

发表者:007james

至于输入定长的问题,可以这样<input name="inp" maxlength="10" onblur="ffffff()">
<script>
ffffff()
{
if inp.length <> 10
{
alert("不够长或者自己补够长度");
}
}
</script>

发表者:realby

function errorcheck2(){
var num=document.form1.test.value;
var i,j,strtemp;
strtemp="0123456789.";
for (i=0;i<num.length;i++) {
j = strtemp.indexof(num.charat(i));
if (j==-1) {
alert(请填写合法数字!);
form1.test.focus();
return false;
}
}
return true;
}

<input type="text" value="value" name="test" maxlength="8" >
提交表单中~允许8位数字

没有评论

  • (Required)
  • (Required, will not be published)