Tips for creating a phone number placeholder that stays in place on a form

I'm looking to display the phone number format as a placeholder in the input field, without it disappearing as the user types.

The standard HTML placeholder disappears as the user starts typing. I want the placeholder to remain visible and guide the user as they input their phone number.

<form action="payonline.html">
     <input type="tel" id="phone" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required placeholder="___ - ___ - ____ ">                             
       <input type="submit" value="Submit">
  </form>

Answer №1

If you want to enhance the user experience for phone input in JavaScript, consider using onkeypress and onkeyup events. Below is an example code snippet using pure JavaScript (assuming you are not utilizing jQuery).

<form action="payonline.html">
     <input type="tel" id="phone" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required placeholder="___ - ___ - ____ " onkeypress="validate_int(this)" onkeyup="phone_number_mask()">                             
       <input type="submit" value="Submit">
  </form>
<script>

 function validate_int(myEvento) {
  if ((myEvento.charCode >= 48 && myEvento.charCode <= 57) || myEvento.keyCode == 9 || myEvento.keyCode == 10 || myEvento.keyCode == 13 || myEvento.keyCode == 8 || myEvento.keyCode == 116 || myEvento.keyCode == 46 || (myEvento.keyCode <= 40 && myEvento.keyCode >= 37)) {
    dato = true;
  } else {
    dato = false;
  }
  return dato;
}
function phone_number_mask() {
      var myMask = "___-___-____";
      var myCaja = document.getElementById("phone");
      var myText = "";
      var myNumbers = [];
      var myOutPut = ""
      var theLastPos = 1;
      myText = myCaja.value;
      //get numbers
      for (var i = 0; i < myText.length; i++) {
        if (!isNaN(myText.charAt(i)) && myText.charAt(i) != " ") {
          myNumbers.push(myText.charAt(i));
        }
      }
      //write over mask
      for (var j = 0; j < myMask.length; j++) {
        if (myMask.charAt(j) == "_") { //replace "_" by a number 
          if (myNumbers.length == 0)
            myOutPut = myOutPut + myMask.charAt(j);
          else {
            myOutPut = myOutPut + myNumbers.shift();
            theLastPos = j + 1; //set caret position
          }
        } else {
          myOutPut = myOutPut + myMask.charAt(j);
        }
      }
      document.getElementById("phone").value = myOutPut;
      document.getElementById("phone").setSelectionRange(theLastPos, theLastPos);
    }


</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Contrasting createMuiTheme and getMuiTheme

When would you choose to use one over the other? What are the key differences in how they operate? ...

I am interested in excluding the seconds and milliseconds from my date and time

I currently display my time in the following format: 5:34 PM I only want to show the hour and minute. How can I achieve this? ...

Issue with Pagination functionality when using Material-UI component is causing unexpected behavior

My database retrieves data based on the page number and rows per page criteria: const { data: { customerData: recent = null } = {} } = useQuery< .... //removed to de-clutter >(CD_QUERY, { variables: { input: { page: page, perPag ...

Issue with Access Denied Error in Internet Explorer 11 when Using AngularJS

Every software development process consists of two essential components. FIRST, the hard work of developing the application. SECOND, the even harder task of making it compatible with the notorious Internet Explorer. Currently, we have an AngularJS (v1.3.1 ...

Struggle arising from the clash between a customized image service and the built-in image element

Dealing with a custom Angular service called Image, I realized that using this name poses a problem as it clashes with Javascript's native Image element constructor, also named Image. This conflict arises when attempting to utilize both the custom Im ...

jQuery Click event not responding on the default Android Mobile Browser for anchor elements

Having trouble triggering a click event on a link element, as the title suggests. Here is the relevant part of the HTML structure: <!-- Table markup here.. --> <td class="text-center"> <a class="text-danger"><i class="fi-trash" ari ...

Content Security Policy in Firefox Extension blocking local DataTables js

After downloading the js for DataTables, I attempted to load it onto my Firefox extension but encountered a Content Security Policy block: Content Security Policy: The page’s settings blocked the loading of a resource at self (“default-src moz-ext ...

The format for a DateTime field in a JSON string array is as follows: yyyy-MM-dd hh:mm:ss

I am working with a JSON array string pulled from a database and I need to format the DateAndTime field into yyyy-MM-dd hh:mm:ss. This formatting needs to be flexible as the data passed through will vary, except for the DateAndTime. Here is my current att ...

Creating Dynamic Web Design: Horizontal Scrolling Window and Adaptive HTML Content

After spending countless hours researching online, I am still unable to find a solution for responsive web design that maintains the aspect ratio of both the window and HTML body. Here are examples of what I'm looking for: original view, stretched le ...

Innovative solutions for seamless transformation of HTML designs into Silverlight 3.0

One of my challenges with clients is getting them on board with web applications. However, I am eager to try something new and explore the potential of Silverlight 3.0. It would be great to see if I can transform some of these applications into fully funct ...

Troubleshooting undefined results when dynamically loading JSON data with $scope values in AngularJS

My input field is connected to the ng-model as shown below. <div ng-app="myApp" ng-controller="GlobalCtrl"> <input type="text" ng-model="FirstName"> {{FirstName}} </div> In my controller, console.log $scope.FirstName shows m ...

Using Javascript to Highlight a Single Row in a Table

Greetings esteemed members of the skilled community at StackOverflow, I must humbly ask for your expertise in solving a dilemma that I am currently facing. The situation is as follows: I have a table generated from an SQL query, and it is crucial for the ...

Determine whether one class is a parent class of another class

I'm working with an array of classes (not objects) and I need to add new classes to the array only if a subclass is not already present. However, the current code is unable to achieve this since these are not initialized objects. import {A} from &apo ...

Utilize Mapbox-GL.JS to animate several points along designated routes

I'm encountering issues with the following example: Animate a point along a route My goal is to add another point and routes in the same map container. Here's what I've tried so far: mapboxgl.accessToken = 'pk.eyJ1IjoicGFwYWJ1Y2t ...

Struggling with Responsive Design Challenges with Grid Material UI?

Encountering an issue while using the Grid Component in my React JS Project. Let's delve into some code and then I'll explain what I aim to achieve with images: Assuming this is the rendered code: <div style="margin:100px 20%; width:80%" &g ...

Substitute the symbol combination (][) with a comma within Node.js

Currently, I am utilizing Node JS along with the replace-in-file library for my project. Within a specific file named functions.js, I have implemented various functions. Furthermore, in another file named index.js, I have added code to call these functio ...

"Encountering a Dojo error where the store is either null or not recognized

I encountered an issue with the function I have defined for the menu item "delete" when right-clicking on any folder in the tree hierarchy to delete a folder. Upon clicking, I received the error message "Store is null or not an object error in dojo" Can s ...

How to Filter, Sort, and Display Distinct Records in an HTML Table with jQuery, JavaScript, and

In the HTML page, there will be a total of 6 tabs labeled A, B, C, D, E, and F along with 2 dropdowns. The expected behavior is as follows: The user will choose a value from the 2 dropdown menus. Based on the selected value, filtering should be applied to ...

Invoking PHP function within a specific class using Ajax

I am currently utilizing Zend Framework. My PHP class is structured as follows: FileName : AdminController.php Path : /admin/AdminController.php Ajax Function : function exportToExcel() { $.ajax({ url: "/admin/AdminController/testFunction", ty ...

The Angular TypeScript service encounters an undefined issue

Here is an example of my Angular TypeScript Interceptor: export module httpMock_interceptor { export class Interceptor { static $inject: string[] = ['$q']; constructor(public $q: ng.IQService) {} public request(config: any) ...