You are viewing limited content. For full access, please sign in.

Question

Question

Inconsistent Jquery Masking

asked on December 7, 2020

Does anyone know why the following Javascript code, in conjunction with "ssn", "phone", or "date" in the CSS Class of a field, works on one form but not another?

$(document).ready(function() {
  $.getScript('https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js', function() {
    $(".ssn input").mask("999-99-9999"); //SSN Mask
    $(".phone input").mask("(999) 999-9999"); //Phone Number Mask
    $(".date input").mask("99/99/9999"); //Date Mask
  });

I've double checked everything I can think of and I can find no differences between the two forms I'm using. One works, one doesn't. Any ideas? Thanks!

0 0

Answer

SELECTED ANSWER
replied on December 7, 2020

Hey Dylan,

It looks like it's a weird part of how that API works. According to the jQuery docs:

The callback is fired once the script has been loaded but not necessarily executed.

Scripts are included and run by referencing the file name:

 

https://api.jquery.com/jquery.getscript/

It might be that your callback function is executing before the script has executed in some instances but not others. It looks like it might work if you replace your syntax with this, per this stack overflow answer:

https://stackoverflow.com/questions/14565365/jquery-getscript-callback-when-script-is-fully-loaded-and-executed

$(document).ready(function () {
    $.getScript('https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js').done(function (script, textStatus) {
        $(".ssn input").mask("999-99-9999"); //SSN Mask
        $(".phone input").mask("(999) 999-9999"); //Phone Number Mask
        $(".date input").mask("99/99/9999"); //Date Mask
    });
});

If that doesn't work, you could wrap your code in a half second time out. It's ugly but if you don't mind your page not being optimized it then it's probably the simplest way to get it working:

$(document).ready(function () {
    $.getScript('https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js').done(function (script, textStatus) {
        setTimeout(function() {
            $(".ssn input").mask("999-99-9999"); //SSN Mask
            $(".phone input").mask("(999) 999-9999"); //Phone Number Mask
            $(".date input").mask("99/99/9999"); //Date Mask
        }, 500) //500 is the time in miliseconds that the timeout should wait to execute the code. 500 is half a second
    });
});

 

0 0
replied on December 7, 2020

Brian, 

Thank you so much for the response! I greatly appreciate it. I tested out the first solution without the 500ms delay and it worked just as expected. Have a wonderful rest of your day, sir, and stay safe!

1 0

Replies

You are not allowed to reply in this post.
You are not allowed to follow up in this post.

Sign in to reply to this post.