Как применить пользовательскую псевдоним ввода с помощью 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} }); 

ВСЕ из следующего приводят к ошибке Uncaught SyntaxError в jquery.inputmask.bundle.js:

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

Отладчик Chrome указывает на проблему со следующей строкой кода входной маски:

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

1 ответ

Решение

Я изучил документацию по jquery.inputmask 3.x. Насколько я понимаю, предпочтительным способом изменения свойств псевдонима является создание нового псевдонима, который наследуется от определения псевдонима по умолчанию.

пример

 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")

A working fiddle is given below

Click to see the fiddle

I have tested this on my chrome browser and found to be working.

To avoid getting the error Uncaught SyntaxError: Avoid using <input data-inputmask="IDR"> поскольку data-inputmask attribute will be evaluated before the jQuery('selector').inputmask("IDR") команда. This will cause a JSONparse error: 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 {}.

Другие вопросы по тегам