Why is mask not being applied?

724 views Asked by At

I want to apply mask to an input element when it receives focus with jquery.maskedinput plugin. But the first time it gets focus, the mask is not there. Only when it receives focus the second time, the mask shows up. How can I make the mask to show the first time it gets focus?

fiddle

html:

 <input type=text id=a />
    <input type=text id=b />

script:

$(document).ready(function () {
    $('#a').on('focus', function () {
        $(this).mask('999');
    });
});
1

There are 1 answers

1
epascarello On BEST ANSWER

The problem is the fact that the widget uses focus() to add the mask. The element is already focused since you are registering it after the event happened.

The way it should work is to register it when the page is created

$(function () {
    $('#a').mask('999')
});

BUT if you want to do it onfocus, you need to trigger focus after removing your event so you do not get stuck in a loop.

$(function () {
    $('#a').on('focus.first', function () {
        $(this).off("focus.first").mask('999').trigger("focus");
    });
});