'Using JQuery to mask input fields. When I refresh a panel that contains those fields the masking stops working

I have several phone number fields that use jquery masking to format the input. See the code below. The fields work great until a combo box change above refreshes a panel that contains those fields. Once the refresh happens my masking stops working.

Any idea why and how to prevent this from happening?

<xp:scriptBlock id="scriptBlock7">
<xp:this.value><![CDATA[
jQuery(function($){
x$("#{id:dayPhone1}").mask("(999) 999-9999? x 9999999", {placeholder : " " } );
x$("#{id:eveningPhone1}").mask("(999) 999-9999? x 9999999", {placeholder : " " } );
x$("#{id:cellular1}").mask("(999) 999-9999? x 9999999", {placeholder : " " } );

});
]]></xp:this.value>
</xp:scriptBlock>


Solution 1:[1]

The jQuery is only run one time. It manipulates the DOM to give the mask effect. Once you run a partial refresh the original DOM is returned to the user and the mask is no longer in effect.

When the partial refresh happens the jQuery code does not know to apply itself back to the mask again. You have a number of choices, but the best is probably:

In the onComplete event of the partial refresh you can call the mask code again to reapply the "Mask". What I don't know is if the mask code will reset the fields or honor the values therein. I that is the case then take a look at the plugin code and see what options you have.

<xp:button value="Label" id="button1" styleClass="startLoginProcess" style="display:none">
        <xp:eventHandler event="onclick" submit="true" refreshMode="partial" refreshId="somethingHere"
            onComplete="applyMaskCodeAgainHere">
        </xp:eventHandler>
</xp:button>

To improve the code above because it looks like you are applying the same mask I suggest using a class selector and simplifying your code to look more like this:

<xp:scriptBlock id="scriptBlock7">
<xp:this.value><![CDATA[
    jQuery(function($){
        $('.phoneMask').mask("(999) 999-9999? x 9999999", {placeholder : " " } );   
    });
]]></xp:this.value>
</xp:scriptBlock>

put a styleClass="phoneMask" on your field :)

Solution 2:[2]

You can remove the mask and reset it...

$(`#${id:dayPhone1}`).val(newPhoneValue).unmask().mask('(00) 00000-0000', {clearIfNotMatch: true});

This worked for me and should solve your problem!

TLDR: .unmask() before .mask()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MarkyRoden
Solution 2