jQuery - Splitting a phone input into three

Thought I'd share this little snippet that helps you to break a single phone number text input into three smaller inputs. This also has a helper that will move the focus from one input to the next as the user types.

/** * Split phone number field into three smaller fields. */ $.fn.splitPhone = function() { // Generate markup for smaller fields. function phone_split(phoneId){ var arrInput = ' - '; arrInput += ' - '; arrInput += ''; return arrInput; }
   this.each(function() {
       var $this = $(this);
       if (!($this.is(':text') || $this.is(':hidden'))) { return; }
       var tabIndex = $this.attr("tabindex") ? $this.attr("tabindex") : 1;

       // Bind behaviors to new small fields.
       var $arrInput = $(phone_split($this.attr("id"))).filter("input");
         $(this).attr("tabindex", tabIndex++);
         // Move focus to next field as user types.
         $(this).bind("keyup", function(e){
           if ($(this).val().length == $(this).attr('maxlength')){
           // As user completes, concatenate values in original field.

       // Hide original field.
       $this.attr("Type", "hidden").removeAttr("tabindex").hide();
       // Don't submit the values of the small fields!
           $(this).attr('disabled', true);

   return this;


Use like so: $('#edit-field-phone-number').splitPhone();

This is really slick! Thanks so much for this!

One small usability problem: if the submit event fails for whatever reason (eg validation), the phone number fields remain disabled. So, a user could enter their phone number wrong, receive a validation error on a different field ("Name is required"), then realize that their phone number is wrong, but be unable to change it.

I got around this by commenting out the line that disables the input field, since I don't care if extra data is submitted. I'll just ignore the extra fields on the back-end. Is that the only reason you're disabling the small fields?

Anyway, great job and thanks for the clean, well-commented code. A pleasure to read and use.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.