1。

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5     <head>
 6         <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
 7         <title>表单验证之只能为数字</title>
 8         <style type="text/css">
 9             .label {float:left; width:120px;}
10             .infobox {width: 200px; }
11             .error {color:red; padding-left: 10px;}
12             .submit {margin-left: 125px; margin-top: 10px; }
13         </style>
14         <script src="jquery-1.5.2.js" type="text/javascript"></script>
15         <script type="text/javascript">
16             $(document).ready(function(){
17                 $('.error').hide();
18                 $('.submit').click(function(event) {
19                     var data = $('.infobox').val();
20                     var len = data.length;
21                     var c;
22                     for(var i=0;i<len;i++) {
23                         //charCodeAt() 方法可返回指定位置的字符的 Unicode 编码。这个返回值是 0 - 65535 之间的整数。
24                         //方法 charCodeAt() 与 charAt() 方法执行的操作相似,
25                         //只不过前者返回的是位于指定位置的字符的编码,而后者返回的是字符子串。
26                         c = data.charAt(i).charCodeAt(0);
27                         if(c==45 && i==0) {
28                             continue;
29                         }
30                         //判断unicode编码
31                         if(c<48 || c>57) {
32                             $('.error').show();
33                             event.preventDefault();
34                             break;
35                         }
36                         else {
37                             $('.error').hide();
38                         }
39                     }
40                 });
41                 
42             });
43         </script>
44         <body>
45             <form id="signup" method="post" action="">
46                 <div>
47                     <span class="label">Your age *</span>
48                     <input type="text" class="infobox" name="userid" />
49                     <span class="error">Only numericals allowed</span>
50                 </div>
51                 <input class="submit" type="submit" value="submit" />
52             </form>
53         </body>
54 </html>

 

posted on 2017-01-18 00:21  Sharpest  阅读(437)  评论(0编辑  收藏  举报