2

Below is one way that we can do masking on input fields. Including below in apex page.

<apex:includeScript value="{!$Resource.jquery}"/>
<apex:includeScript value="{!$Resource.jMaskedInput}"/>

and masked classes as below,

<apex:outputLabel for="tel" value="Telephone"/>
<apex:inputText id="tel" styleClass="tel-mask"/>

and script as below.

<script>
$(document).ready(function() {
$(".tel-mask").mask("(999) 999-9999");
});
</script>

Do we have a way to get this for a InputField in Visualforce pages rather than having to hard-code masks for every field?

4

Assuming you mean you want that particular code on your visualforce pages, you could turn it into an <apex:component>. Your component would just be:

<apex:component>
    <apex:includeScript value="{!$Resource.jquery}"/>
    <apex:includeScript value="{!$Resource.jMaskedInput}"/>

    <script>
    $(document).ready(function() {
        $(".tel-mask").mask("(999) 999-9999");
    });
    </script>
</apex:component>

You can also use <apex:attribute> to add an attribute to the component so the calling visualforce page can specify the class name, or even just pass the selector in wholesale.

One important thing to note is that depending on where you put the component, you may have other functions bound to $(document).ready after this one is bound - if they add new elements to the DOM, they may not be added before this script is run. You can avoid this by putting the component at the bottom of your page.

Additionally, adding jQuery again after you've already added it to the page once causes the global jQuery object to get overwritten.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.