如何使用 jquery 应用自定义别名输入掩码?

How do I apply a custom alias inputmask using jquery?

我正在尝试在 Yii2 表单输入上使用输入掩码。这是我的代码:

var IDR={"alias":"numeric","prefix":"Rp","digits":0,"digitsOptional":false,"decimalProtect":true,"groupSeparator":",","radixPoint":".","radixFocus":true,"autoGroup":true,"autoUnmask":true,"removeMaskOnSubmit":true};
Inputmask.extendAliases({"IDR": {"alias":"numeric","prefix":"Rp","digits":0,"digitsOptional":false,"decimalProtect":true,"groupSeparator":",","radixPoint":".","radixFocus":true,"autoGroup":true,"autoUnmask":true,"removeMaskOnSubmit":true} }); 

以下所有内容都会在 jquery.inputmask.bundle.js 上产生错误 Uncaught SyntaxError:

jQuery('selector').inputmask(IDR)
jQuery('selector').inputmask("IDR")
jQuery('selector').inputmask(eval(IDR))
jQuery('selector').inputmask({'mask':'IDR'})
jQuery('selector').inputmask({'alias':'IDR'})

Chrome 调试器指出以下 inputmask 代码行存在问题:

42: dataoptions = JSON.parse("{" + attrOptions + "}")), dataoptions) {

我查看了 jquery.inputmask 的文档 3.x.From 我的理解是更改别名属性的首选方法是创建一个继承自默认别名定义的新别名。

示例

 Inputmask.extendAliases({
      'numeric': {
        "prefix":"Rp",
        "digits":0,
        "digitsOptional":false,
        "decimalProtect":true,
        "groupSeparator":",",
        "radixPoint":".",
        "radixFocus":true,
        "autoGroup":true,
        "autoUnmask":true,
        "removeMaskOnSubmit":true
      }
    }); 

Inputmask.extendAliases({
     'IDR': {
        alias: "numeric", //it inherits all the properties of numeric    
       "prefix":"Rpoverrided"//overrided the prefix property   
      }
});

现在像这样将输入掩码应用到您的选择器

jQuery('selector').inputmask("IDR")

下面给出了一个有效的fiddle

Click to see the fiddle

我已经在我的 chrome 浏览器上进行了测试,发现可以正常工作。

避免出现 Uncaught SyntaxError: 错误 避免使用 <input data-inputmask="IDR">,因为 data-inputmask 属性将在 jQuery('selector').inputmask("IDR") 命令之前计算。这将导致 JSONparse 错误:https://github.com/RobinHerbots/Inputmask.

data-inputmask attribute You can also apply an inputmask by using the data-inputmask attribute. In the attribute you specify the options wanted for the inputmask. This gets parsed with $.parseJSON (for the moment), so be sure to use a well-formed json-string without the {}.