简体   繁体   English

如何阻止将数字输入到contenteditable元素中

[英]How to stop numbers from being entered in a contenteditable element

JSFiddle: https://jsfiddle.net/mqfntbws/ JSFiddle: https ://jsfiddle.net/mqfntbws/

I have a contenteditable span in which I want to prevent users from typing special characters or numbers. 我有一个contenteditable span ,希望防止用户键入特殊字符或数字。 The problem is, I'm able to prevent special characters but it won't work on numbers. 问题是,我可以防止使用特殊字符,但对数字不起作用。 Anyone know what I'm doing wrong? 有人知道我在做什么错吗?

HTML: HTML:

<span required="" contenteditable="" placeholder="First Name" aria-required="true"></span>

JS: JS:

$('span[contenteditable]').on('keypress', function (event) {
      var regex = new RegExp("^[A-z]+$");
            var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
            if (!regex.test(key) && !((event.keyCode>=46 && event.keyCode<=58) || event.keyCode==8 || event.keyCode==9 || (event.keyCode>=37 && e.keyCode<=40))) {
         console.log(">>>");
                 event.preventDefault();
                 return false;
            }
});

As you appear to be using jQuery, you can make full use of the isNumeric() function within the API. 当您似乎正在使用jQuery时,可以充分利用API中的isNumeric()函数。

From the documentation : 文档中

The $.isNumeric() method checks whether its argument represents a numeric value. $ .isNumeric()方法检查其参数是否表示数字值。 If so, it returns true. 如果是这样,则返回true。 Otherwise it returns false. 否则返回false。 The argument can be of any type. 参数可以是任何类型。

So using this cleans up your if statement immensely. 因此,使用此命令可以极大地清理if语句。

if(!regex.test(key) || $.isNumeric(key))

Leaving you with the following: 留下以下内容:

$('span[contenteditable]').on('keypress', function (event) {

    var regex = new RegExp("^[A-z]+$");
    var key = String.fromCharCode(event.which);

    if (!regex.test(key) || $.isNumeric(key)) {

      event.preventDefault();
      return false;
    }
});

I have forked and updated your original fiddle with a working example: https://jsfiddle.net/GH05T/mqfntbws/6/ 我已经用一个有效的示例分叉并更新了您的原始提琴: https : //jsfiddle.net/GH05T/mqfntbws/6/

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

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