readtheBook readtheBook - 7 months ago 84
jQuery Question

How do I apply a custom alias inputmask using jquery?

I'm trying to use a inputmask on a Yii2 form input. Here is my code:

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} });

ALL of the following produce the error Uncaught SyntaxError on jquery.inputmask.bundle.js:


Chrome debugger points to a problem with the following line of inputmask code:

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


I have looked into the documentation of jquery.inputmask 3.x.From my understanding the preferred way to alter properties for an alias is by creating a new alias which inherits from the default alias definition.


      'numeric': {

     'IDR': {
        alias: "numeric", //it inherits all the properties of numeric    
       "prefix":"Rpoverrided"//overrided the prefix property   

Now apply the input mask to your selector like this


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"> because the data-inputmask attribute will be evaluated before the jQuery('selector').inputmask("IDR") command. This will cause a JSONparse error:

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 {}.