Text field mask does not work in mobile environment

Asked

Viewed 1,807 times

3

I used the following code in jQuery to mask the field telefone for example.

jQuery(document).ready(function () {
    $("#telefone").mask("(99)9999.9999");
});

This code works perfectly on the computer, but on the mobile, only appears the formatting waiting to be typed something, but when something is typed, the mask is not applied, thus mixing the numbers with the other characters.

Example of what happens:

jQuery(function($){
$("#telefone").mask("(99) 9999-9999");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/digitalBush/jquery.maskedinput/1.4.1/dist/jquery.maskedinput.min.js"></script>

<strong>No desktop: </strong>
<input type="text" id="telefone">
<br><br>
<strong>No celular: </strong>
<input type="text" value="(__)____.____">

Does anyone have any idea how to fix this?

Note: If you enter the correct number amount from the phone, even if you have other characters in the field, it applies the filter by pressing enter, or clicking outside the field.

  • 1

    I’ve had this problem too - for me the solution was to use a mask in pure javascript.

1 answer

3


One option is to use a mask in pure javascript. Using regex might be something like:

document.getElementById('telefone').addEventListener('input', function (e) {
  var aux = e.target.value.replace(/\D/g, '').match(/(\d{0,2})(\d{0,4})(\d{0,4})/);
  e.target.value = !aux[2] ? aux[1] : '(' + aux[1] + ') ' + aux[2] + (aux[3] ? '-' + aux[3] : '');
});
<input type="text" id="telefone" placeholder="(99) 9999.9999"/>

  • 1

    Done, it worked perfectly! Thanks @Lucascosta

Browser other questions tagged

You are not signed in. Login or sign up in order to post.