How to add an input mask to a phone number using jQuery
In this article, you will learn about how to add an input mask to a phone number using jQuery.
An input mask is nothing but a bunch of string of characters that denotes how the input number will be on the basis of some conditions. Basically, it provides a predefined format so that the user can understand how the number should be input. jQuery comes with an amazing and lightweight plugin to make a mask on input. Its syntax is very simple and easy to use. Let’s see an example of it to understand things more clearly.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Input Mask</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<p>Enter Your Phone Number:</p>
<form>
<input type="text" name="phone" id="phone">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/5.0.7/jquery.inputmask.min.js"></script>
<script src="app.js"></script>
</body>
</html>
Here, in the HTML file, we simply linked jQuery, the input mask plugin from CDN. You may download these locally but to make things simple we use the online version. Finally, we take an input field so that the user can type his number. Let’s see the jQuery code where we implement the functionality to make things work.
JavaScript
$(document).ready(function(){
$('#phone').inputmask('(999)-999-9999',{placeholder:'(XXX)-XXX-XXXX'})
});
Here, we catch our id and type inputmask that comes with the plugin and we define a format. Now the user can not give any other input like string or special character except number. Let’s see the output below
Output
Here, you can see that we are getting the number in the same format that we have set before. It only accept the number and you will not be able to input any string or any special character or more than the formatted numbers.
This is a basic overview of the input mask of a phone number by using jQuery and you may use a different format based on your need.