For the phone wrote the following mask:

$("#phone").inputmask("(8 999 999 99 99)|(+7 999 999 99 99)|(+7 99999 9 99 99)|(8 99999 9 99 99)|(+7 9999 99 99 99)|(8 9999 99 99 99)"); 

How can I make the first mask (of a mobile phone) be in priority and be substituted first when filling in the field?

  • 6
    I vote for closing this question, because the author has found a solution (see the remote answer, if reputation is enough), did not tell anyone about it and dumped it. - Pavel Mayorov
  • eight
    Maybe in this case it makes sense to give an answer to the question posed? Others may face the same issue in the future. - XelaNimed

1 answer 1

The most flexible option will be for you to hang the listener of the keyup event and change the masks depending on the entered value. I will give an example of changing the mask for numbers with 8 or +7. With this approach, you can fully control the priority of masks and cases of their application relative to the entered value.

 let $phone = $('#phone'); //Маска ΠΏΠΎ ΡƒΠΌΠΎΠ»Ρ‡Π°Π½ΠΈΡŽ $phone.inputmask("9 999 9999-999"); $phone.on("keyup", function(event) { //ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ ΠΏΠΎΠ»Π΅ Π±Π΅Π· маски var value = $(event.target).inputmask("unmaskedvalue"); //Π”Π°Π»Π΅Π΅ ΠΌΠΎΠ³ΡƒΡ‚ Π±Ρ‹Ρ‚ΡŒ Π»ΡŽΠ±Ρ‹Π΅ ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠΈ, Ρ‡Ρ‚ΠΎΠ±Ρ‹ ΠΈΠ·ΠΌΠ΅Π½ΠΈΡ‚ΡŒ маску Π½Π° Π½ΡƒΠΆΠ½ΡƒΡŽ.. //НапримСр:сдСлаСм для Π½ΠΎΠΌΠ΅Ρ€ΠΎΠ² +7 if (value.length === 2 && value === "+7") { $phone.inputmask("+7 (999) 999-99-99"); } //Если ΠΏΠΎΠ»Π΅ очистили, ΡƒΠ±Π΅Ρ€Π΅ΠΌ маску ΠΈ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅, ΠΌΠΎΠΆΠ΅ΠΌ Π΅Ρ‰Π΅ Π²Π΅Ρ€Π½ΡƒΡ‚ΡŒ маску ΠΏΠΎ ΡƒΠΌΠΎΠ»Ρ‡Π°Π½ΠΈΡŽ ΠΏΡ€ΠΈ нСобходимости if (value === "") $phone.inputmask('remove').val(""); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://rawgit.com/RobinHerbots/Inputmask/3.x/dist/jquery.inputmask.bundle.js"></script> <label for="phone">НомСр</label> <input type="text" id="phone" />