Issues with jQuery Masked plugin

Kiwanax picture Kiwanax · May 13, 2013 · Viewed 8.7k times · Source

This is my field with mask:

$('#Cellphone').mask("(99)9999-9999?9", { placeholder: " " });
  1. I want to clear the mask when my input lost its focus. Is there a way to do it? Something like an option of the plugin...

    $('#Cellphone').mask("(99)9999-9999?9", { 
        placeholder: " ", 
        clearOnLostFocus: true 
    });
    

    or into a blur function:

    $('#Cellphone').blur(function() {
        // clear the mask here.
    });
    
  2. I want to change my mask dynamically. I'm using this function, and works pretty good...

    $('#Cellphone').keyup(function () {
        var newValue = $(this).val()
            .replace("(", "")
            .replace(")", "")
            .replace(" ", "")
            .replace("-", "")
            .replace("?", "");
    
        if (newValue.length > 10) {
            $(this).mask("(99)9-9999-9999", { placeholder: " " });
        }
    });
    

    BUT... When I press backspace with the content of this field selected, my mask stops to work. Any idea why this is happening?

Thank you, guys!

Answer

mccannf picture mccannf · May 13, 2013

The clearOnLostFocus option works when you have not filled the mask correctly. I.e. if you have not entered all the digits, then leave the input, it will clear it.

$('#cellphone').mask("(99)9999-9999?9", { placeholder: " ", clearOnLostFocus: true });

If you want the input field to blank when losing focus even when the digits inside the field match the mask, then you need to use a blur event. In the event callback, empty the field, and re-apply the input mask:

$("#cellphone").blur(function() {
   $(this).val(""); 
   $(this).mask("(99)9999-9999?9", { placeholder: " " });
});

The reason backspace or delete causes problems is because the plugin is trying to apply the new mask to a line of text that is incorrect. So in your keyup function, you need to check if the new mask is in place (length of the input field will be 15) and if the key pressed was a backspace (code = 8) or a delete key (code = 46). If so, then you need to reapply the old mask.

$('#cellphone').keyup(function (event) {
    if ($(this).val().length > 14 && ((event.keyCode == 8)||(event.keyCode == 46))) {
        $(this).mask("(99)9999-9999?9", { placeholder: " " });
    } else {
            var newValue = $(this).val()
                .replace("(", "")
                .replace(")", "")
                .replace(" ", "")
                .replace("-", "")
                .replace("?", "");

            if (newValue.length > 10) {
                $(this).mask("(99)9-9999-9999", { placeholder: " " });
            }
    }
});

JSFiddle here with all of the above.