I am using the jQuery inputmask plugin, version: 5.0.9-beta.4
.
I have a username field that should only be masked if first 3 characters entered by the user is equal to 784
, else the mask should be removed.
var inputMsk = $('#txtUsername').inputmask('999-9999-9999999-9');
inputMsk.inputmask('remove');
$('#txtUsername').on('input', function() {
var fieldValue = $(this).val();
if (fieldValue.startsWith('784')) {
if ($('#txtUsername').inputmask) {
inputMsk = $('#txtUsername').inputmask('999-9999-9999999-9');
}
} else {
if ($('#txtUsername').inputmask) {
inputMsk.inputmask('remove');
}
}
});
The above code generates an error in the console when I a enter 784
and then remove the 4
.
The error is:
Uncaught TypeError: f is not a function
The console identifies the following code from the inputmask.js
plugin file as the source of the error:
keypressEvent: function (e, t, i, a, o) {
var c = this.inputmask || this,
u = c.opts,
f = c.dependencyLib,
p = c.maskset,
d = c.el,
h = f(d),//----------on this line error is generated
m = e.key;
I don't have much previous experience with the inputmask plugin, but I worked on your code example and I arrived at a solution that seems to work.
First, the Type Error is being thrown by the plugin's code. I don't know exactly what is causing it, but it looks to me to have something to do with the timing of when the mask is removed and the handlers for the keyup
event are fired. This gave me a hunch that wrapping the .inputmask('remove')
call in a setTimeout
with a timeout value of 0
could help - and it did. For more information on this, see: Why is setTimeout(fn, 0) sometimes useful?.
The setTimeout
prevented the error, but it did not clear the mask. So I tried re-setting the mask with an empty string, .inputmask('')
, instead of calling .inputmask('remove')
. This seems to have given the desired effect.
const $input = $('#txtUsername');
$input.on('input', function() {
const fieldValue = $input.val();
if (fieldValue.startsWith('784')) {
$input.inputmask('999-9999-9999999-9');
} else {
setTimeout(() => {
$input.inputmask('');
}, 0);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/inputmask@5.0.8/dist/jquery.inputmask.min.js"></script>
<input id="txtUsername">