readtheBook readtheBook - 2 months ago 40
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:

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


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

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

Answer

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.

Example

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

Now apply the input mask to your selector like this

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"> because the data-inputmask attribute will be evaluated before the jQuery('selector').inputmask("IDR") command. 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 {}.