How to Create a Simple Phone Number Picker

Phone numbers, besides names and emails, are a many frequently used hit information in online forms. Phone series fields are customarily designed in a approach that requires users to form a numbers in regulating their keyboards. This process frequently formula in false information input.

To reduce user submit errors and urge a user knowledge of your site, we can emanate a GUI that allows users to fast enter their phone number, in a approach that is identical to date pickers.

Useful Calendar Date Picker Scripts For Web Developers

Useful Calendar Date Picker Scripts For Web Developers

Calendars can be seen frequently in many web pages currently generally in blogs and personal websites. As for…Read more

In this tutorial, you’ll see how to add a elementary phone series picker to an submit field. We’ll use HTML5, CSS3 and JavaScript to get to a GUI we can see and exam in a demo below. We’ll also put regular expressions in use to make certain users unequivocally enter a current phone number.

1. Create a Phone Number Field

First, create an submit field with a dial idol on a right that will open a dial shade on click. The dial idol usually looks like 9 black boxes, organised 3 by 3, contingency like what we see on a unchanging phone.

I’m regulating a tel submit form for correct HTML5 semantics, though we can also use a text submit form if we want.

div id="dialWrapper"
    submit id="phoneNo" type="tel"
    img id="dialIcon" src="dialIcon.png"
/div
HTML Base of a Phone Number PickerHTML Base of a Phone Number Picker

HTML Base of a Phone Number Picker
2. Create a Dial Screen

The dial screen is a grid of numbers from 0 to 9 and some special characters. It can be done with either a HTML table or JavaScript.

Here, I’ll uncover we how to emanate a dial shade list in JavaScript. You can, of course, supplement a list directly in a HTML source formula if we cite it that way.

First, emanate a new 'table' component in a DOM by regulating a createElement() method. Also give it a 'dial' identifier.

/* Create dial shade */
var dial = document.createElement('table');
    dial.id = 'dial';

Add a for loop to insert a 4 rows of a dial list with it. Then, for any row, run another for loop in sequence to supplement 3 cells per row. Mark any cell with a 'dialDigit' class.

for (var rowNum = 0; rowNum  4; rowNum++) {
    var quarrel = dial.insertRow(rowNum);
    for (var colNum = 0; colNum  3; colNum++) {
        var dungeon = row.insertCell(colNum);
        cell.className = 'dialDigit';
        cell.textContent = ((colNum + 1) + (rowNum * 3)).toString();
    }
}

The dual for loops above calculate a digits that go into a cells of a dial list — a values of a cell.textContent skill — in a following way:

(colNum + 1) + (rowNum * 3)
/* initial quarrel */
(0 + 1) + (0 * 3) = 1
(1 + 1) + (0 * 3) = 2
(2 + 1) + (0 * 3) = 3
/* second quarrel */
(0 + 1) + (1 * 3) = 4
(1 + 1) + (1 * 3) = 5
(2 + 1) + (1 * 3) = 6
/* etc. */

The final quarrel is different, as it consists of two special characters, - and + that are used in phone series formats to brand informal codes, and a series 0.

To emanate a final quarrel to a dial screen, supplement a following if matter to a middle for loop.

for (var rowNum = 0; rowNum  4; rowNum++) {
  var quarrel = dial.insertRow(rowNum);
  for (var colNum = 0; colNum  3; colNum++) {
    /* if final quarrel */
    if (rowNum === 3) {
      dungeon = row.insertCell(colNum);
      cell.textContent = '-';
      cell.className = 'dialDigit';
      dungeon = row.insertCell(colNum);
      cell.textContent = '0';
      cell.className = 'dialDigit';
      dungeon = row.insertCell(colNum);
      cell.textContent = '+';
      cell.className = 'dialDigit';
      break;
    }
    dungeon = row.insertCell(colNum);
    cell.className = 'dialDigit';
    cell.textContent = ((colNum + 1) + (rowNum * 3)).toString();
  }
}

The dial shade is now complete, supplement it to a #dialWrapper HTML enclosure we combined in Step 1 by regulating two DOM methods:

  1. the querySelector() process to select a container
  2. the appendChild() process to append a dial screen — hold in a dial non-static — to a container
document.querySelector('#dialWrapper').appendChild(dial);
Dial Screen Table Without StylingDial Screen Table Without Styling

Dial Screen Table though Styling
3. Style a Dial Screen

To make it some-more attractive, style a dial screen with CSS.

You don’t indispensably have to hang with my styling, though don’t forget to add user-select:none; skill to a #dial container so that while a user is clicking on a digits, a content won’t get comparison by a cursor.

#dial {
      width: 200px;
      height: 200px;
      border-collapse: collapse;
      text-align: center;
      position: relative;
      -ms-user-select: none;
      -webkit-user-select: none;
      -moz-user-select: none;
      user-select: none;
      color: 
      box-shadow: 0 0 6px 
}
.dialDigit {
      border: 1px plain 
      cursor: pointer;
      background-color: rgba(255,228,142,.7);
}
Dial Screen with StylingDial Screen with Styling

Dial Screen Table with Styling
4. Show a Dial Screen on Click

First, supplement a visibility:hidden; impression sequence to #dial in a above CSS to hide a dial screen by default. it’ll be usually shown when a user clicks on a dial icon.

Then, supplement a click eventuality handler to a dial idol with JavaScript to toggle a visibility of a dial screen.

To do so, we need to use a aforementioned querySelector() and a addEventListener() methods. The latter attaches a click event to a dial idol and calls a tradition toggleDial() function.

The toggleDial() duty changes a visibility of a dial shade from dark to visible, and back.

document.querySelector('#dialIcon').addEventListener('click', toggleDial);

function toggleDial() {
    dial.style.visibility =
    dial.style.visibility === 'hidden' || dial.style.visibility === ''
    ? 'visible' : 'hidden';
}
5. Add a Functionality

Add a tradition duty that inputs digits into a phone series field on a click of a cells of a dial screen.

The dialNumber() duty appends a digits one by one to a textContent skill of a submit margin noted with a #phoneNo identifier.

phoneNo = document.querySelector('#phoneNo');
function dialNumber() {
    phoneNo.value += this.textContent;
}
dialDigits = document.querySelectorAll('.dialDigit');
for (var i = 0; i  dialDigits.length; i++) {
    dialDigits[i].addEventListener('click', dialNumber);
}

Now, we have a working dial screen to submit phone series field.

To keep adult with a CSS, change a credentials tone of a digits in their :hover and :active (when a user clicks on it) states.

.dialDigit:hover{
      background-color: rgb(255,228,142);
}
.dialDigit:active{
      background-color: 
}
6. Add Regular Expression Validation

Add a simple regex validation to countenance a phone series while a user enters a digits into a submit field. According to a validation manners we use, a phone series can usually start with possibly a series or a + character, and accept a - impression afterwards.

Beginner’s Guide to Regular Expression (Regex)

Beginner’s Guide to Regular Expression (Regex)

A unchanging countenance is a set of characters combining a settlement that can be searched in a string.…Read more

You can see a cognisance of my unchanging countenance on a screenshow next combined with a Debuggex app.

Debuggex VisualizationDebuggex Visualization

Regex cognisance from debuggex.com

You can also validate a phone number as per a phone series format of your nation or region.

Create a new Regular Expression object, and store it in a pattern variable. Also emanate a tradition validate() duty that checks if a entered phone series complies with a unchanging expression, and if it’s at slightest 8 characters long.

When a submit doesn’t validate, a validate() duty needs to give feedback to a user.

I’m adding a red border to a submit margin when a submit is invalid, though we can surprise user in other ways, for instance, with blunder messages.

pattern = new RegExp("^(\+\d{1,2})?(\d+\-*\d+)*$");
function validate(txt) {
  // during slightest 8 characters for a current phone no.
  if (!pattern.test(txt) || txt.length  8) {
    phoneNo.style.border = '2px plain red';
    lapse false;
  } else
    phoneNo.style.border = 'initial';
  lapse true;
}
7. Perform a Validation

The validate() functions needs to be called in sequence to perform a validation. Call it from a dialNumber() duty we combined in Step 5 in sequence to countenance a value of a phoneNo variable.

Note that we also combined an additional validation for limit characters (can’t be some-more than 15) by regulating an if statement.

function dialNumber() {
	var val = phoneNo.value + this.textContent;
	// limit characters allowed, 15
	if (val.length  15) lapse false;
	validate(val);
	phoneNo.value = val;
}

Your phone series picker is now ready, check out a final demo below.

Add Comment