网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的考试资料:

 

标题 jQuery实现只允许输入数字和小数点的方法
内容
    本文实例讲述了jQuery实现只允许输入数字和小数点的方法。分享给大家供大家参考,具体如下:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <script src="jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    //示例代码:
    //只允许输入数字与.:<input type="text" name="test" id="test" onkeydown="checkKeyForFloat(this.value,event)" />
    //只允许输入数字 :<input type="text" name="test2" id="test2" onkeydown="checkKeyForNum(this.value,event)" />
    //只允许输入数字与小数点
    function checkKeyForFloat(value, e) {
     var isOK = false;
     var key = window.event ? e.keyCode : e.which;
     if ((key > 95 && key < 106) || //小键盘上的0到9
     (key > 47 && key < 60) || //大键盘上的0到9
     (key == 110 && value.indexOf(".") < 0) || //小键盘上的.而且以前没有输入.
     (key == 190 && value.indexOf(".") < 0) || //大键盘上的.而且以前没有输入.
     key == 8 || key == 9 || key == 46 || key == 37 || key == 39 //不影响正常编辑键的使用(8:BackSpace;9:Tab;46:Delete;37:Left;39:Right)
    ) {
      isOK = true;
     } else {
      if (window.event) //IE
      {
       e.returnValue = false; //event.returnValue=false 效果相同.
      }
      else //Firefox
      {
       e.preventDefault();
      }
     }
     return isOK;
    }
    //只允许输入数字
    function checkKeyForInt(value, e) {
     var isOK = false;
     var key = window.event ? e.keyCode : e.which;
     if ((key > 95 && key < 106) || //小键盘上的0到9
     (key > 47 && key < 60) || //大键盘上的0到9
     key == 8 || key == 9 || key == 46 || key == 37 || key == 39 //不影响正常编辑键的使用(8:BackSpace;9:Tab;46:Delete;37:Left;39:Right)
    ) {
      isOK = true;
     } else {
      if (window.event) //IE
      {
       e.returnValue = false; //event.returnValue=false 效果相同.
      }
      else //Firefox
      {
       e.preventDefault();
      }
     }
     return isOK;
    }
    //设置有自定义属性 dtype 的文本框 允许输入的范围
    function setDType() {
     $(":text[dtype]").each(function () {
      var dtype = $(this).attr("dtype");
      var isOK = true;
      switch (dtype) {
       case "number":
        $(this).css("ime-mode", "disabled").keydown(function (event) {
         isOK = checkKeyForFloat($(this).val(), event);
         if (!isOK) {
          //$(this).SuperFocus("", 500);
         }
         return isOK;
        });
        break;
       default:
        break;
      }
     });
    }
    </script>
    <script type="text/javascript">
    $(function () {
     setDType();
    });
    </script>
    </head>
    <body>
    年龄: <input type="text" maxlength="3" onkeydown="checkKeyForInt(this.value,event)"/><br />
    身高:<input type="text" maxlength="5" dtype="number" />
    </body>
    </html>
    希望本文所述对大家jQuery程序设计有所帮助。
随便看

 

在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。

 

Copyright © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/5/20 13:58:35