How to Separate Dial Code From Smart Phone Form Field Dropdown

Overview

Would you like to separate the dial code from the flag dropdown when using the Smart Phone form field? Perhaps you’d like to style this element separately in your form. You can easily separate the dial code with a small PHP snippet and in this tutorial we’ll show you how.

Setup

By default, the dial code is hidden inside the flag dropdown until you click on the dropdown to open it. In this tutorial, we’re going to separate that field so it will be displayed beside the flag.

1) Creating your form

First you’ll need to create a form and add a Phone form field. From the Field Options on the field, make sure the Format dropdown has Smart selected.

Add a phone form field to your form and from the field options, be sure to select Smart from the dropdown

2) Adding the code snippet

Next, you’ll need to copy and paste this code snippet to your site.

This will apply to all Phone form fields that use the Smart format.

/**
 * Separating the dial code from the flag dropdown on the Smart Phone form field.
 *
 * @link https://wpforms.com/developers/how-to-separate-dial-code-from-smart-phone-form-field-dropdown/
 *
 */
function wpf_dev_smart_phone_field_separate_dial_code() {
    ?>
	<script type="text/javascript">
		jQuery( document ).on( 'wpformsReady', function() {
			var $el = jQuery( '.wpforms-smart-phone-field' ),
				iti = $el.data( 'plugin_intlTelInput' ),
				options;
			// Options are located in different keys of minified and unminified versions of jquery.intl-tel-input.js.
			if ( iti.d ) {
				options = Object.assign( {}, iti.d );
			} else if ( iti.options ) {
				options = Object.assign( {}, iti.options );
			}
			if ( ! options ) {
				return;
			}
			$el.intlTelInput( 'destroy' );
			options.separateDialCode = true;
			$el.intlTelInput( options );
		} );
	</script>
	<?php
}
add_action( 'wpforms_wp_footer', 'wpf_dev_smart_phone_field_separate_dial_code' );

As you can see, the dial code is now displaying when the form loads.

The dial code is now separate from the flag dropdown and can be styled in the next step.

3) Styling the dial code

Finally, we can now add some CSS to the site in order to style this element on the page.

.iti__selected-dial-code {
    font-size: 10px !important;
    font-weight: bold !important;
    margin-left: 8px !important;
    margin-right: 8px !important;
}

Now our dial code has a smaller font-size and a little more padding to the right and left.

With this CSS added, you can now see the dial code appears beside the flag but a little smaller in the font-size.

And that’s it! You can now separate the dial code from the flag dropdown. Would you like to add some additional validation for the Phone field? Check out our tutorial on How to Provide Additional Phone Field Validation.

Action Reference: wpforms_wp_footer