如何使用jQuery在输入文本字段中仅允许数字(即使复制粘贴时)? [英] How to allow only numbers (even when copy-pasted) in input text field using jQuery?

查看:70
本文介绍了如何使用jQuery在输入文本字段中仅允许数字(即使复制粘贴时)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此jQuery代码,仅允许在输入文本字段中输入数字.

I am using this jQuery code to allow only numbers to be entered in input text field.

jQuery(document).ready(function() {     
    jQuery( '.only_numbers' ).keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if (jQuery.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A, Command+A
            ((e.keyCode === 65) && (e.ctrlKey === true || e.metaKey === true)) || 
             // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });
});

这很好,除了一个小问题.它不允许在该字段中粘贴任何内容.仅当字符串包含所有数字字符时,如何允许用户将字符串粘贴到字段中?

This works fine, except one small problem. It does not allow anything to be pasted in the field. How can I allow user to paste a string in the field, only if the string contains all numeric characters?

此外,如果我可以对只允许输入字母的输入文本字段执行相同的操作,那就太棒了.

Also, it will be awesome if I could do the same for input text fields allowing only alphabets.

推荐答案

您的HTML

 <input type='text' />

您的Jquery

 $('input').on('paste', function (event) {
  if (event.originalEvent.clipboardData.getData('Text').match(/[^\d]/)) {
    event.preventDefault();
  }
});

$("input").on("keypress",function(event){
                if(event.which <= 48 || event.which >=57){
                    return false;
                }
            });

工作码笔 https://codepen.io/anon/pen/pwEXyg

这篇关于如何使用jQuery在输入文本字段中仅允许数字(即使复制粘贴时)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆