如何剪切、复制、粘贴和选择'只允许数字的文本框'使用JQuery

How to Cut Copy Paste and Select in a 'Only number alowed textbox' using JQuery?

本文关键字:数字 JQuery 使用 文本 复制 何剪切 选择 许数字      更新时间:2023-09-26

在文本框中,用户只能输入数字(0-9)、逗号、点和退格

我们希望用户在文本框中操作(Ctrl +X,Ctrl+V,Ctrl+C, Ctrl+A);但不能在文本框中输入V、X、A和C。如何将业务逻辑应用于以下代码?

function isDecimalNumber(eve, element) {
 var charCode = (eve.which) ? eve.which : event.keyCode
 if (charCode == 44 || charCode == 46 || charCode == 8 || (charCode > 48 && charCode < 57))
  return true; 
 return false;
}    

请使用此提琴仅供参考:https://jsfiddle.net/jdxn1Lmn/5/

你可以这样做。

使用我在下面创建的实用程序:

  var clipboardUtility = {
      getCopiedText: function (params) {
          var input = params || {},
              e = input.event,
              incomingText;
          if (e) {
              if (e.originalEvent.clipboardData) {
                  incomingText = (e.originalEvent || e).clipboardData.getData('text/plain');
              } else if (window.clipboardData) {
                  incomingText = window.clipboardData.getData('Text');
              }
          }
          return incomingText;
      }
  };

并将粘贴事件附加到jQuery上

    $("#txt-subject-name").bind("paste", onPatseEvent);

,并将以下代码放在粘贴事件上:

function onPatseEvent(e) {
    var incomingText = clipboardUtility.getCopiedText({
        event: e
    });
    //Regex way of numeric input only
    if (/^'d+$/g.test(incomingText)) {
        e.preventDefault();
            alert('Pasting values that contains non numeric values are not allowed');
    }
},