Graham
Graham

Reputation: 1960

Make an input field mask with dots

I have an input field like this:

<input type="text" placeholder=".........">

When a user enters the field with some text I would like the dots to be replaced with the letters. So if I entered "Ha" in it. The user sees this:

<input type="text" placeholder="Ha.......">

And so on for the other letters

I've seen a lot of examples with dates, numbers and ip's but am still quite not sure on how to reproduce this to my problem.

Upvotes: 1

Views: 2177

Answers (1)

mylee
mylee

Reputation: 1333

The solution to this would be slightly complicated.

First, create a new duplicated input which will act as the "placeholder" as it will float behind the real input field. Then attach event listener on the real input and fill the value into the "placeholder".

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  </head>
  <body>
    <div style="position: relative; width: 400px; height: 24px;">
        <input type="text" style="width: 100%; height: 100%; position: absolute; z-index: 1; color: #ccc" id="placeholder">
        <input type="text" style="width: 100%; height: 100%; position: absolute; z-index: 2; background-color: transparent; color: #000" id="realInput">
    </div>
    <script>
      function fillPlaceholder(){
        //suppose you want 9 characters for the placeholder
        var limit = 9;
        var text = $("#realInput").val();
        while (text.length < limit) {
            text += ".";
        }
        $("#placeholder").val(text);
      }
      $("#realInput").on("input", fillPlaceholder);
      fillPlaceholder();
    </script>
  </body>
</html>

Upvotes: 4

Related Questions