第一种:输入整形判断functiongetEvent(){if(document.all){returnwindow.event;}//foriefunc=getEvent.caller;while(func!=null){vararg0

第一种:输入整形判断

总结js实现验证html文本框输入只能为数字(html文本框只允许输入数字)  总结js实现验证html文本框输入只能为数字 第1张

function getEvent() { if (document.all) { return window.event; } //for ie func = getEvent.caller; while (func != null) { var arg0 = func.arguments[0]; if (arg0) { if ((arg0.constructor == Event || arg0.constructor == MouseEvent) || (typeof (arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) { return arg0; } } func = func.caller; } return null; } function isnumber() { var ev = getEvent();       if (ev.keyCode == 8) return true; //可删除 if (ev.keyCode < 48 || ev.keyCode > 57) return false; }

<input />

 

第二种:输入浮点和整形判断

function isnumber(obj) { if (isNaN(obj.value)) { obj.value = ""; return false; } return true; }

<input />

 

第三种:推荐,能够判断中文输入法

/** * @description 给指定文本框绑定输入验证(适合非中文输入法输入验证),如验证输入必须为数字VerifyInput("txtNumber","[^\\d]"); * @param controlId 需要绑定文本框id * @param regex 验证正则表达式(取反),如果正则表达式中有斜杠,使用双斜杠 */function VerifyInput(controlId, regex) { var myRegExp = new RegExp(regex, 'g'); $("#" + controlId).bind("input propertychange", function () { this.value = this.value.replace(myRegExp, ''); });}

页面调用

<input />

$(function () {    VerifyInput("txtNumber", "[^\\d]");//验证文本框输入必须为数字});

参考:https://www.cnblogs.com/llguanli/p/7340708.html

 

第四种:限制只能输入整数和浮点判断,推荐

function verifyIsNumberStart(control) { if (!control.value.match(/^[\+\-]?\d*?\.?\d*?$/)) control.value = control.t_value; else control.t_value = control.value; if (control.value.match(/^(?:[\+\-]?\d+(?:\.\d+)?)?$/)) control.o_value = control.value } function verifyIsNumberEnd(control) { if (!control.value.match(/^(?:[\+\-]?\d+(?:\.\d+)?|\.\d*?)?$/)) control.value = control.o_value; else { if (control.value.match(/^\.\d+$/)) control.value = 0 + control.value; if (control.value.match(/^\.$/)) control.value = 0; control.o_value = control.value } }

<input type="text" onkeypress="verifyIsNumberStart(this)" onkeyup="verifyIsNumberStart(this)" onblur="verifyIsNumberEnd(this)" ondragenter="return false"/>

 

第五种:https://***.com/questions/15520410/disable-ime-mode-in-google-chrome

 

转载请说明出处
知优网 » 总结js实现验证html文本框输入只能为数字(html文本框只允许输入数字)

发表评论

您需要后才能发表评论