简体   繁体   English

将文本字段限制为仅数字的最佳方法?

[英]Best way to restrict a text field to numbers only?

I'm using the following Javascript to restrict a text field on my website to only accept numerical input, and no other letters or characters.我正在使用以下 Javascript 来限制我网站上的文本字段只接受数字输入,而不接受其他字母或字符。 The problem is, it REALLY rejects all other key inputs, like ctrl - A to select the text, or even any other browser functions like ctrl - T or ctrl - W while the text box is selected.问题是,它真的拒绝所有其他键输入,例如ctrl - A选择文本,甚至任何其他浏览器功能,例如ctrl - Tctrl - W在选择文本框时。 Does anyone know of a better script to only allow numerical input, but not block normal commands (that aren't being directly input into the field)?有谁知道更好的脚本只允许数字输入,但不阻止正常命令(不是直接输入到字段中)? Thanks Here is the code I'm using now:谢谢这是我现在使用的代码:

function numbersonly(e, decimal) 
{
    var key;
    var keychar;

    if (window.event) 
        key = window.event.keyCode;
    else if (e) 
        key = e.which;
    else 
        return true;

    keychar = String.fromCharCode(key);

    if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27))
       return true;     
    else if ((("0123456789").indexOf(keychar) > -1))
       return true;
    else if (decimal && (keychar == "."))
       return true;        
    else
       return false;
}

Edit: None of the solutions provided have solved my problem of allowing commands like ctrl - A while the text box is selected.编辑:提供的解决方案都没有解决我在选择文本框时允许像ctrl - A这样的命令的问题。 That was the whole point of my asking here, so I have gone back to using my original script.这就是我在这里提问的全部意义,所以我又回到了使用我原来的脚本。 Oh well.哦,好吧。

This is something I made another time for just numbers, it will allow all the formatters as well.这是我再次为数字所做的事情,它也将允许所有格式化程序。

jQuery jQuery

$('input').keypress(function(e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
        a.push(i);

    if (!(a.indexOf(k)>=0))
        e.preventDefault();
});​

Try it试试看

http://jsfiddle.net/zpg8k/ http://jsfiddle.net/zpg8k/

As a note, you'll want to filter on submit/server side as well, for sake of pasting/context menu and browsers that don't support the paste event.请注意,为了粘贴/上下文菜单和不支持粘贴事件的浏览器,您还需要在提交/服务器端进行过滤。

Edit to elaborate on multiple methods编辑以详细说明多种方法

I see you're bouncing around the 'accepted' answer, so I'll clear something up.我看到你在“接受”的答案周围蹦蹦跳跳,所以我会澄清一些事情。 You can really use any of the methods listed here, they all work.你真的可以使用这里列出的任何方法,它们都有效。 What I'd personally do is use mine for live client side filtering, and then on submit and server side use RegEx as suggested by others.我个人会做的是使用我的实时客户端过滤,然后在提交和服务器端按照其他人的建议使用 RegEx。 However, no client side by itself will be 100% effective as there is nothing stopping me from putting document.getElementById('theInput').value = 'Hey, letters.';但是,没有任何客户端本身会是 100% 有效的,因为没有什么能阻止我放置document.getElementById('theInput').value = 'Hey, letters.'; in the console and bypassing any clientside verification (except for polling, but I could just cancel the setInterval from the console as well).在控制台中并绕过任何客户端验证(轮询除外,但我也可以从控制台取消setInterval )。 Use whichever client side solution you like, but be sure you implement something on submit and server side as well.使用您喜欢的任何客户端解决方案,但请确保您也在提交和服务器端实现了一些东西。

Edit 2 - @Tim Down编辑 2 - @Tim Down

Alright, per the comments I had to adjust two things I didn't think of.好吧,根据评论我不得不调整两件我没有想到的事情。 First, keypress instead of keydown, which has been updated, but the lack of indexOf in IE (seriously Microsoft!?) breaks the example above as well.首先,keypress 而不是 keydown,它已经更新,但是 IE 中缺少 indexOf(认真的微软!?)也打破了上面的例子。 Here's an alternative这是一个替代方案

$('input').keypress(function(e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
        a.push(i);

    if (!($.inArray(k,a)>=0))
        e.preventDefault();
});​

New jsfiddle: http://jsfiddle.net/umNuB/新的 jsfiddle: http : //jsfiddle.net/umNuB/

这适用于 IE、Chrome 和 Firefox:

<input type="text" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));" />
     .keypress(function(e)
               {
                 var key_codes = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 8];

                 if (!($.inArray(e.which, key_codes) >= 0)) {
                   e.preventDefault();
                 }
               });

You need Backspace and Delete keys too ;)您也需要退格键和删除键;)

http://jsfiddle.net/PgHFp/ http://jsfiddle.net/PgHFp/

<html>
<head>
<title>Test</title>
<script language="javascript">
function checkInput(ob) {
  var invalidChars = /[^0-9]/gi
  if(invalidChars.test(ob.value)) {
            ob.value = ob.value.replace(invalidChars,"");
      }
}
</script>
</head>

<body>
    <input type="text" onkeyup="checkInput(this)"/>
</body>
</html>

I use this:我用这个:

    oEl.keypress(function(ev)
    {
        var sKey = String.fromCharCode(ev.which);
        if (!sKey.match(/[0-9]/) || !sKey === "") 
            ev.preventDefault();            
    });

The advantage is, that every key which does not provide an input to the field is still allowed, so you don't have to worry about every single special key.优点是,仍然允许每个不提供字段输入的键,因此您不必担心每个特殊键。 Even combos like CTRL + R do still work.即使像 CTRL + R 这样的组合仍然有效。

EDIT As this is not working in Firefox I had to modify the function a little:编辑因为这在 Firefox 中不起作用,所以我不得不稍微修改一下函数:

    oEl.keypress(function(ev)
    {
        var iKeyCode = ev.which || ev.keyCode;
        var aSpecialKeysForFirefox = [8, 9, 13, 27, 37, 38, 39, 40, 46];
        var sKey = String.fromCharCode(iKeyCode);
        if (sKey !== "" && $.inArray(iKeyCode, aSpecialKeysForFirefox ) < 0 && !sKey.match(/[0-9]/)) {
            ev.preventDefault();
        }
    });

Explanation All Browsers handle jquerys keypress event differently.说明所有浏览器都以不同的方式处理 jquery 按键事件。 To make it work in FF the $.inArray check is added.为了使其在 FF 中工作,添加了 $.inArray 检查。 As firefoxs keypress-event doesn't trigger when combinations like strg+tab are used, but the others do, the key.match approach still adds a little value to the latter, as it enables those combinations.由于使用 strg+tab 等组合时,firefoxs keypress-event 不会触发,但其他组合会触发,因此 key.match 方法仍然为后者增加了一点价值,因为它启用了这些组合。

Just use regex to get rid of any non number characters whenever a key is pressed or the textbox loses focus.每当按下键或文本框失去焦点时,只需使用正则表达式即可摆脱任何非数字字符。

var numInput;
window.onload = function () {   
    numInput = document.getElementById('numonly');
    numInput.onkeydown = numInput.onblur = numInput.onkeyup = function()
    {
        numInput.value = numInput.value.replace(/[^0-9]+/,"");
    }
}

The only event that contains information about the character typed is keypress .唯一包含输入字符信息的事件是keypress Anything character-related you may infer from the keyCode property of keydown or keyup events is unreliable and dependent on a particular keyboard mapping.您可以从keydownkeyup事件的keyCode属性推断出的任何与字符相关的内容都是不可靠的,并且依赖于特定的键盘映射。 The following will prevent non-numeric keyboard input all major browsers by using the character obtained from the keypress event.以下将通过使用从keypress事件获得的字符来防止所有主要浏览器的非数字键盘输入。 It won't prevent the user from pasting or dragging non-numeric text in.它不会阻止用户粘贴或拖动非数字文本。

var input = document.getElementById("your_input");

input.onkeypress = function(evt) {
    evt = evt || window.event;
    if (!evt.ctrlKey && !evt.metaKey && !evt.altKey) {
        var charCode = (typeof evt.which == "undefined") ? evt.keyCode : evt.which;
        if (charCode && !/\d/.test(String.fromCharCode(charCode))) {
            return false;
        }
    }
};

Maybe you are using bootstrap.也许您正在使用引导程序。 If so, this may suffice:如果是这样,这可能就足够了:

<input type="text" data-mask="9999999"> 

Input mask 输入掩码

添加<script type="text/javascript" src="jquery.numeric.js"></script>然后使用

 $("element").numeric({ decimal: false, negative: false });

The following code is something I use extensively.以下代码是我广泛使用的代码。 I found the script in a forum, but modified and expanded it to accommodate my needs:我在论坛中找到了该脚本,但对其进行了修改和扩展以满足我的需求:

<script type="text/javascript">
    // Restrict user input in a text field
    // create as many regular expressions here as you need:
    var digitsOnly = /[1234567890]/g;
    var integerOnly = /[0-9\.]/g;
    var alphaOnly = /[A-Za-z]/g;
    var usernameOnly = /[0-9A-Za-z\._-]/g;

    function restrictInput(myfield, e, restrictionType, checkdot){
        if (!e) var e = window.event
        if (e.keyCode) code = e.keyCode;
        else if (e.which) code = e.which;
        var character = String.fromCharCode(code);

        // if user pressed esc... remove focus from field...
        if (code==27) { this.blur(); return false; }

        // ignore if the user presses other keys
        // strange because code: 39 is the down key AND ' key...
        // and DEL also equals .
        if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
            if (character.match(restrictionType)) {
                if(checkdot == "checkdot"){
                    return !isNaN(myfield.value.toString() + character);
                } else {
                    return true;
                }
            } else {
                return false;
            }
        }
    }
</script>

Different usage methods would be:不同的使用方法是:

<!-- To accept only alphabets -->
<input type="text" onkeypress="return restrictInput(this, event, alphaOnly);">
<!-- To accept only numbers without dot -->
<input type="text" onkeypress="return restrictInput(this, event, digitsOnly);">
<!-- To accept only numbers and dot -->
<input type="text" onkeypress="return restrictInput(this, event, integerOnly);">
<!-- To accept only numbers and only one dot -->
<input type="text" onkeypress="return restrictInput(this, event, integerOnly, 'checkdot');">
<!-- To accept only characters for a username field -->
<input type="text" onkeypress="return restrictInput(this, event, usernameOnly);">

shorter way and easy to understand:更短的方式,易于理解:

$('#someID').keypress(function(e) { 
    var k = e.which;
    if (k <= 48 || k >= 58) {e.preventDefault()};
});

This is a variation on Robert's answer that allows a single decimal point to be entered.这是罗伯特答案的变体,允许输入一个小数点。 If a decimal point has already been entered, only numbers are accepted as input.如果已经输入了小数点,则只接受数字作为输入。

JSFiddle - decimal number input JSFiddle - 十进制数字输入

// Allow only decimal number input

$('#decimalInput').keypress(function (e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
    a.push(i);

    // allow a max of 1 decimal point to be entered
    if (this.value.indexOf(".") === -1) {
        a.push(46);
    }

    if (!(a.indexOf(k) >= 0)) e.preventDefault();

    $('span').text('KeyCode: ' + k);
});

I know that there are already many answers but for the sake of simplicity i would like to add another answer which is simple and self explanatory in which we do not have to remember keycodes and it also works across all browsers .我知道已经有很多答案,但为了简单起见,我想添加另一个简单且不言自明的答案,我们不必记住键码,并且它也适用于所有浏览器

 document.getElementById('myinput').onkeydown = function(e) { console.log(e.key); //console.log(e.target.value); switch (e.key) { case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "0": case "Backspace": return true; break; case ".": if (e.target.value.indexOf(".") == -1) { return true; } else { return false; } break; default: return false; } }
 <input type="text" placeholder="Enter Value" id="myinput" />

this will enable the numpad inputs also.这也将启用小键盘输入。

.keydown(function(event){                                     
    if(event.keyCode == 8 || event.keyCode == 46)             
        return true;                                         
    if(event.keyCode >= 96 && event.keyCode <= 105)           
        return true;                                          
    if(isNaN(parseInt(String.fromCharCode(event.keyCode),10)))
       return false;                                          
}); 

In order to block anything but numbers from being input into a text field but still allowing for other buttons to work (such as delete, shift, tab, etc.) look at a reference of the Javascript key codes ;为了阻止除数字之外的任何内容输入文本字段,但仍允许其他按钮工作(例如删除、移位、制表符等),请查看Javascript 键代码参考 anything from 65 on up (to 222) can be blocked.从 65 到 222 的任何内容都可以被阻止。

Using Jquery and Javascript, that would look like:使用 Jquery 和 Javascript,看起来像:

$('#textFieldId').keydown(function(event) {
    if ( event.keyCode > 64 ) {
        event.preventDefault();
    }
});

The key codes will be the same in Javascript whether or not Jquery is used.无论是否使用 Jquery,关键代码在 Javascript 中都是相同的。

Here is my solution: a combination of the working ones below.这是我的解决方案:以下工作的组合。

var checkInput = function(e) {
        if (!e) {
            e = window.event;
        }

        var code = e.keyCode || e.which;

        if (!e.ctrlKey) {

            //46, 8, 9, 27, 13 = backspace, delete, tab, escape, and enter
            if (code == 8 || code == 13 || code == 9 || code == 27 || code == 46)
                return true;
            //35..39 - home, end, left, right
            if (code >= 35 && code <= 39)
                return true;
            //numpad numbers
            if (code >= 96 && code <= 105)
                return true;
            //keyboard numbers
            if (isNaN(parseInt(String.fromCharCode(code), 10))) {
                e.preventDefault();
                return false;
            }
        }
        return true;
    };

I came across your question while trying to figure this out myself.我在试图自己解决这个问题时遇到了你的问题。 Here is the solution that I came up with.这是我想出的解决方案。

// Prevent user from entering non-numeric characters in number boxes.
(function (inputs) {
    var input;
    var f = function (e) {
        var unicodeRe = /U\+(\d+)/;
        // Chrome doesn't support the standard key property, so use keyIdentifier instead.
        // Instead of the actual character that "key" returns, keyIdentifier returns
        // A string such as "U+004F" representing the unicode character.

        // For special characters (e.g., "Shift", a string containing the name of the key is returned.)
        var ch = e.key || e.keyIdentifier;
        var match = ch.match(unicodeRe);
        // keyIdentifier returns a unicode. Convert to string.
        if (match) {
            ch = String.fromCharCode(Number.parseInt(match[1], 16));
        }
        console.log(ch);
        if (ch.length === 1 && /[^0-9]/.test(ch)) {
            if (!/[\b]/.test(ch)) { // Don't prevent backspace.
                e.preventDefault();
            }
        }
    };
    for (var i = 0, l = inputs.length; i < l; i += 1) {
        input = inputs[i];
        input.onkeydown = f;
    }
}(document.querySelectorAll("input[type=number],#routeFilterBox")));

Edit: I've discovered that my solution does not allow the user to enter numbers via the numpad in Chrome.编辑:我发现我的解决方案不允许用户通过 Chrome 中的数字键盘输入数字。 The 0-9 keypad keys seem to be returning the character "`" for 0 and AI for the rest of the number keys. 0-9 键盘键似乎为 0 返回字符“`”,为其余数字键返回 AI。

It's worth pointing out that no matter how tightly you manage to control this via the front end (Javascript, HTML, etc), you still need to validate it at the server, because there's nothing to stop a user from turning off javascript, or even deliberately posting junk to your form to try to hack you.值得指出的是,无论您设法通过前端(Javascript、HTML 等)多么严格地控制它,您仍然需要在服务器上对其进行验证,因为没有什么可以阻止用户关闭 javascript,甚至故意向您的表单发布垃圾内容以试图破解您。

My advice: Use the HTML5 markup so that browsers which support it will use it.我的建议:使用 HTML5 标记,以便支持它的浏览器使用它。 Also use the JQuery option previously suggested (the inital solution may have flaws, but it seems like the comments have been working through that).还可以使用之前建议的 JQuery 选项(初始解决方案可能有缺陷,但似乎评论已经解决了这个问题)。 And then do server-side validation as well.然后也进行服务器端验证。

All of the answers are outdated, lengthy and will cause annoyance to your users.所有的答案都是过时的、冗长的,并且会给您的用户带来烦恼。 Most of them don't even filter or allow pasted content.他们中的大多数甚至不过滤或允许粘贴的内容。

Instead of filtering the input, do some validation before submitting the form and then also server-side.不要过滤输入,而是在提交表单之前进行一些验证,然后在服务器端进行验证。

HTML has validation included: HTML 的验证包括:

<input type="number" pattern="[0-9]+">

This also enables the number keyboard on mobile.这也启用了移动设备上的数字键盘。

This is my plugin for that case:这是我用于这种情况的插件:

 (function( $ ) {
    $.fn.numbers = function(options) {
      $(this).keypress(function(evt){
          var setting = $.extend( {
                'digits' : 8
              }, options);
          if($(this).val().length > (setting.digits - 1) && evt.which != 8){
              evt.preventDefault(); 
          }
          else{
              if(evt.which < 48 || evt.which > 57){
                if(evt.keyCode != 8){
                    evt.preventDefault();  
                }
              }
          }
      });
    };
  })( jQuery );

Use:使用:

 $('#limin').numbers({digits:3});
 $('#limax').numbers();

There is my current solution of numeric input, need to test in different browsers but seems to work有我当前的数字输入解决方案,需要在不同的浏览器中进行测试,但似乎有效

Support comma and period delimiter (czech native is comma), space and numpad/keyboard numbers input.支持逗号和句点分隔符(捷克本地为逗号)、空格和小键盘/键盘数字输入。 Allow Ctrl+C Ctrl+A or Ctrl+X, arrow navigation and delete block Ctrl+V.允许 Ctrl+C Ctrl+A 或 Ctrl+X,箭头导航和删除块 Ctrl+V。 React on escape key by blurring input.通过模糊输入对转义键做出反应。

Watch my Coffee script:观看我的咖啡脚本:

(($) ->
  $.fn.onlyNumbers = ->
    @each ->
      $(@).keydown (e) ->
        # get code of key
        code = if e.keyCode then e.keyCode else e.which

        return $(@).blur() if code is 27 # blur on escape
        return if code in [46, 8, 9, 13] # 46, 8, 9, 27, 13 = backspace, delete, tab, escape, and enter
        return if (e.ctrlKey or e.metaKey) and code in [65, 67, 88] # ctrl|command + [a, c, x]
        return if code in [96..105] # numpad numbers
        return if code in [48..57] # numbers on keyboard
        return if code in [35..39] # 35..39 - home, end, left, right
        return if code in [188, 190, 32] # comma, period, space
        return if code in [44] # comma, period,

        e.returnValue = false # IE hate you
        e.preventDefault();

      $(@).keypress (e) ->
        code = if e.keyCode then e.keyCode else e.which
        return if code in [44, 46, 32] # comma, period, space
        return if code in [48..57] # numbers on keyboard
        e.returnValue = false # IE hate you
        e.preventDefault();

) jQuery

You can get compiled Javascript here http://goo.gl/SbyhXN你可以在这里获得编译好的 Javascript http://goo.gl/SbyhXN

My functions:我的功能:

$('.input_integer_only').on('input', function(e) {
    $(this).val($(this).val().replace(/[^0-9]/g, ''));
});


$('.input_float_only').on('input', function(e) {
    var $var = $(this).val().replace(/[^0-9\.]/g, '');
    var $aVar = $var.split('.');

    if($aVar.length > 2) {
        $var = $aVar[0] + '.' + $aVar[1];
    }

    $(this).val($var);
});

You can make changes to accept the keycode for Ctrl keys: 17, 18, 19, 20. Then your code will be like:您可以进行更改以接受 Ctrl 键的键码:17、18、19、20。然后您的代码将如下所示:

function numbersonly(e, decimal) {
var key;
var keychar;

if (window.event) 
    key = window.event.keyCode;
else if (e) 
    key = e.which;
else 
    return true;

keychar = String.fromCharCode(key);

if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27) || (key==17) || (key==18) || (key==19) || (key==20))
   return true;     
else if ((("0123456789").indexOf(keychar) > -1))
   return true;
else if (decimal && (keychar == "."))
   return true;        
else
   return false;
}
  document.getElementById('myinput').onkeydown = function(e) {
      if(!((e.keyCode > 95 && e.keyCode < 106)
      || (e.keyCode > 47 && e.keyCode < 58) 
      || e.keyCode == 8
      || e.keyCode == 9)) {
        return false;
      }
  }

You can do like this to accept only Numbers in text Box,您可以这样做以仅接受文本框中的数字,

 function onChange(event){
   var ckeckChars = /[^0-9]/gi;
   if(checkChars.test(event.target.value)) {
        event.target.value = event.target.value.replace(ckeckChars,"");
  }

This JavaScript function will be used to restrict alphabets and special characters in Textbox , only numbers, delete, arrow keys and backspace will be allowed.此 JavaScript 函数将用于限制 Textbox 中的字母和特殊字符,只允许使用数字、删除、箭头键和退格键。 JavaScript Code Snippet - Allow Numbers in TextBox, Restrict Alphabets and Special Characters JavaScript 代码片段 -允许文本框中的数字,限制字母和特殊字符

Tested in IE & Chrome.在 IE 和 Chrome 中测试。

JavaScript function JavaScript 函数

<script type="text/javascript">
    /*code: 48-57 Numbers
      8  - Backspace,
      35 - home key, 36 - End key
      37-40: Arrow keys, 46 - Delete key*/
    function restrictAlphabets(e){
        var x=e.which||e.keycode;
        if((x>=48 && x<=57) || x==8 ||
            (x>=35 && x<=40)|| x==46)
            return true;
        else
            return false;
    }
</script>

HTML Source Code with JavaScript带有 JavaScript 的 HTML 源代码

<html>
    <head>
        <title>JavaScript - Allow only numbers in TextBox (Restrict Alphabets and Special Characters).</title>
        <script type="text/javascript">
            /*code: 48-57 Numbers
              8  - Backspace,
              35 - home key, 36 - End key
              37-40: Arrow keys, 46 - Delete key*/
            function restrictAlphabets(e){
                var x=e.which||e.keycode;
                if((x>=48 && x<=57) || x==8 ||
                    (x>=35 && x<=40)|| x==46)
                    return true;
                else
                    return false;
            }
        </script>
    </head>
<body style="text-align: center;">
    <h1>JavaScript - Allow only numbers in TextBox (Restrict Alphabets and Special Characters).</h1>
    <big>Enter numbers only: </big>
    <input type="text" onkeypress='return restrictAlphabets(event)'/>
</body>

</html>

Refrence 参考

I am using below in Angular to restrict character我在 Angular 下面使用来限制字符

in HTML在 HTML 中

For Number Only仅限号码

<input
 type="text"
 id="score"
 (keypress) ="onInputChange($event,'[0-9]')"
 maxlength="3"
 class="form-control"> 

for Alphabets Only仅适用于字母

<input
     type="text"
     id="state"
     (keypress) ="onInputChange($event,'[a-zA-Z]')"
     maxlength="3"
     class="form-control"> 

In TypeScript在打字稿中

 onInputChange(event: any, inpPattern:string): void {   
        var input = event.key; 
        if(input.match(inpPattern)==null){
         event.preventDefault();
        }
      }

You can handle te event on html by introducing keypresshandler function您可以通过引入 keypresshandler 函数来处理 html 上的 te 事件

function keypresshandler(event)
{
     var charCode = event.keyCode;

     //You condition
     if (charCode == 58 ){

        event.preventDefault();

        return false;
     }        
} 

Javascript is often used on the browser client side to perform simple tasks that would otherwise require a full postback to the server. Javascript 通常用于浏览器客户端来执行简单的任务,否则这些任务将需要完整的回发到服务器。 Many of those simple tasks involve processing text or characters entered into a form element on a web page, and it is often necessary to know the javascript keycode associated with a character.许多这些简单的任务涉及处理输入到网页表单元素中的文本或字符,并且通常需要知道与字符关联的 javascript 键码。 Here is a reference.这是一个参考。

Press a key in the text box below to see the corresponding Javascript key code.在下面的文本框中按一个键以查看相应的 Javascript 键代码。

 function restrictCharacters(evt) { evt = (evt) ? evt : window.event; var charCode = (evt.which) ? evt.which : evt.keyCode; if (((charCode >= '48') && (charCode <= '57')) || (charCode == '44')) { return true; } else { return false; } }
 Enter Text: <input type="text" id="number" onkeypress="return restrictCharacters(event);" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM