Home / Admin / How to Restrict Countries Inside Smart Phone Form Fields
Duplicate Snippet

Embed Snippet on Your Site

How to Restrict Countries Inside Smart Phone Form Fields

<10
Code Preview
php
<?php
/**
 * Restrict countries inside the Smart Phone form field
 *
 * @link   https://wpforms.com/how-to-restrict-countries-inside-smart-phone-form-fields/
 */
 
function wpf_dev_smart_phone_field_restrict_countries() {
    ?>
 
    <script type="text/javascript">
        jQuery(document).on('wpformsReady', function () {
            jQuery('.wpforms-smart-phone-field').each(function () {
                var $el = jQuery(this),
                    iti = $el.data('plugin_intlTelInput'),
                    options;
 
                if (!iti) {
                    return;
                }
 
                // Retrieve options based on the provided instance.
                if (iti.s) {
                    options = Object.assign({}, iti.s);
                } else if (iti.options) {
                    options = Object.assign({}, iti.options);
                } else {
                    return;
                }
 
                $el.intlTelInput('destroy');
 
                // Set the only countries to US, UK and Canada
                options.onlyCountries = ['us', 'ca', 'gb']; // 'us' for United States, 'ca' for Canada, 'gb' for United Kingdom
 
                // Put a country code here according to this list: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
 
                // Set initial country if needed
                options.initialCountry = 'us';
 
                // Re-initialize the plugin with the updated options
                $el.intlTelInput(options);
 
                // Restore hidden input name after intlTelInput is reinitialized.
                $el.siblings('input[type="hidden"]').attr('name', 'wpforms[fields][' + options.hiddenInput + ']');
            });
        });
    </script>
 
    <?php
}
 
add_action('wpforms_wp_footer_end', 'wpf_dev_smart_phone_field_restrict_countries', 30); 

Comments

Add a Comment