Angelux
Angelux

Reputation: 99

Jquery input mask set starting input point after prefix

Hello Im using the jquery input mask, and I'm stucked.

I have a pattern for phone number (+420 XXX XXX XXX) where X are digits.

This is my current code

 phoneInputs.inputmask("+999 999 999 999", {
        "placeholder": "+420 ___ ___ ___",
        "onincomplete": function(){
            $(this).addClass("incomplete");
        },
        "oncomplete": function(){
            $(this).removeClass("incomplete");
        }
    });

Everything works fine but the problem is when I start typing into the input I rewrite the +420 number.

I would like to start writing on the index of first normal phone number (not the +420 part). Is it possible somehow? Using this inputmask or jQuery? Thank you

Upvotes: 2

Views: 6866

Answers (2)

setilight
setilight

Reputation: 61

You can include your prefix in the mask definition, taking care to escape any reserved characters.

phoneInputs.inputmask("\\+420 999 999 999", { "escapeChar": "\\" });

Upvotes: 1

cнŝdk
cнŝdk

Reputation: 32145

One tricky solution, is to use two separate inputs one disabled input for the prefix and the second one is for the dynamic phone number, along with some CSS styling to get the style as it was only one field:

HTML:

<input type="text" id="prefix" value="+420" disabled/>
<input type="text" id="phoneInput" />

JS:

let phoneInputs = $("#phoneInput");
phoneInputs.inputmask(" 999 999 999", {
  "placeholder": " ___ ___ ___",
  "onincomplete": function() {
    $(this).addClass("incomplete");
  },
  "oncomplete": function() {
    $(this).removeClass("incomplete");
  }
});

Note:

  • You need to update the inputmask placeholder to " ___ ___ ___", so it doesn't consider the +420 part.
  • And to take the full input value you just need to combine the two inputs values.

Demo:

This is a working demo:

let phoneInputs = $("#phoneInput");
phoneInputs.inputmask(" 999 999 999", {
  "placeholder": " ___ ___ ___",
  "onincomplete": function() {
    $(this).addClass("incomplete");
  },
  "oncomplete": function() {
    $(this).removeClass("incomplete");
  }
});
input[type="text"]#prefix {
  -webkit-appearance: none!important;
  text-decoration:none;
  text-align: right;
  width: 35px;
  border: 1px solid gray;
  border-right: 0px;
  margin: 0 0 0 -7px;
  background: white;
}

input[type="text"]#phoneInput {
  -webkit-appearance: none!important;
  border: 1px solid gray;
  margin-left: -4px;
  border-left: 0px;
  outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.jqueryscript.net/demo/Easy-jQuery-Input-Mask-Plugin-inputmask/dist/jquery.inputmask.bundle.min.js"></script>

<label>Phone number:</label>
<input type="text" id="prefix" value="+420" disabled/>
<input type="text" id="phoneInput" />

Upvotes: 1

Related Questions