输入框限制

来源:互联网 发布:八达岭老虎伤人知乎 编辑:程序博客网 时间:2024/06/18 06:12
Web 前端项目,经常会遇到输入控件只能输入汉字,字母或者数字等等,本文介绍了一种简单的方法。比如只能输入字母,则在你输入的时候进行判断,如果你输入的是数字,则会把数字自动的替换为空,优点是代码简洁,不需要考虑很多状况,缺点是界面输入不够友好。
 <input id="count" name="count" onblur="computeCode()" maxlength="50" type="text" value="500" class="txt" style="width: 220px"  
  onkeyup='this.value=this.value.replace(/\D/gi,"")' />

输入字母或者数字的时候,有必要将输入法进行限制。

style="ime-Model:disabled" 
针对于输入字母的
<input id="stockno" oncontextmenu="return false" style="ime-Mode: disabled" onpaste="return false;"  onkeyDown="numAndLetter(this.id)" onblur="this.value=half_en(this.id)">
/** *  letter and num */function numAndLetter(obj) {
   $("#" + obj).keypress(
     function(e) {
       if (e.which != 8 && e.which != 0 && e.which != 9 && !((48 <= e.which && e.which <= 57)|| (65 <= e.which && e.which <= 90) || (97 <= e.which && e.which <= 122))) {return false;}});}
/** *  half_en format */function half_en(obj) {var str = $("#" + obj).val();if (IsNullOrEmpty(str)) {return "";}var reg = new RegExp(/^[0-9a-zA-Z]+$/);if (!reg.test(str)) {return "";}return str;}
针对于输入数字的
<input id="insurance" size="8" oncontextmenu="return false"style="ime-Mode: disabled" onkeyDown="onlyNum(this.id)" onpaste="return false;" maxValue="7"onblur="this.value=moneyFormat(this.id)" type="money">
/** * only num */function onlyNum(obj) {$("#" + obj).keypress(function(e) {if (e.which != 8 && e.which != 0 && e.which != 9&& (e.which < 48 && 45 != e.which|| e.which > 57)) {return false;}else if(45 == e.which){   return true;}var value = parseInt($("#" + obj).val().replace(/,/g, "").replace(/-/g, ""));var map = {key4 : '999',key5 : '9999',key6 : '99999',key7 : '999999',key8 : '9999999',key9 : '99999999'};var integer = $("#" + obj).attr("maxValue");var mapValue = map['key' + integer];if (value > parseInt(mapValue)) {return false;}if (value > 214748364) {return false;} else if (value == 214748364&& (56 == e.which || 57 == e.which)) {return false;}});}
/** *  money format */function moneyFormat(obj) {var str = $("#" + obj).val();if (IsNullOrEmpty(str)) {return "";}str = str.replace(/,/g, "");var reg = new RegExp(/^-?[0-9]+$/);if (!reg.test(str)) {return "";}str = parseInt(str);if (str > 2147483647) {str = 2147483647;}return (str).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');}
                                             
0 0
原创粉丝点击