Home > other >  Password mask for input part with Jquery
Password mask for input part with Jquery

Time:04-08

I'm creating an input for a credit card, I need to separate it into 4 groups of 4 digits,
the problem is that I need to mask the second and third group as a password.

example ( 0 0 0 0 - * * * * - * * * * - 0 0 0 0).

Would it be possible to make this mask in just one input? I only managed to make an input for each group but it was very strange.

Detail I can only use Jquery 1.3.2

CodePudding user response:

This is a possible solution using vanilla js. In this solution the original input is masked by span which will contain the formatted credit card number.

Code

document.querySelector(".credit-card>input").addEventListener("input", (event) => {
      document.querySelector(".credit-card>span").textContent = mask(event.target.value);
    });

    function mask(text) {
      let masked = "";
      for (let i = 0; i < text.length; i  ) {
        if (i % 4 === 0 && i !== 0) masked  = "-"
        if (i > 3 && i < 12) {
          masked  = "*";
        } else {
          masked  = text[i];
        }
      }
      return masked;
    }
.credit-card {
      position: relative;
      height: 2rem;
      width: 150px;
    }

    .credit-card > input {
      position: absolute;
      top: 0;
      left: 0;
      height: 100%;
      width: 100%;
      border: 1px solid gray;
      outline: none;
      color: #fff;
    }

    input:focus {
      border: 1px solid red;
    }

    .credit-card > span {
      position: absolute;
      top: 0;
      left: 0;
      height: 100%;
      width: 100%;
      z-index: 3;
      user-select: none;
      pointer-events: none;
      display: flex;
      align-items: center;
      justify-content: center;
    }
<div >
    <input type="text" maxlength="16"/>
    <span></span>
  </div>

  • Related