Two jquery masks in one field

3

Can anyone help me?

I have an input in which it is CPF / CNPJ, how do I make a mask containing two different values for the same field? And how would the code contain an additional telephone field? In other words, masks on the input cpf / cnpj and masks on the phone, I just got from cpf, I can not get the phone together!

<input type="text" name="cpf" id="cpf">
<input type="text" name="tel" id="tel">

$(document).ready(function(){
var SPMaskBehavior = function (val) {
return val.replace(/\D/g, '').length === 11 ? '000.000.000.00' : '00.000.000/0000-01';
},
spOptions = {
onKeyPress: function(val, e, field, options) {
field.mask(SPMaskBehavior.apply({}, arguments), options);
}
};

$('#cpf').mask(SPMaskBehavior, spOptions);
});

link

    
asked by anonymous 16.04.2018 / 00:42

2 answers

1

This code works, it extracts from the documentation:

var options =  {
  onKeyPress: function(cpf, e, field, options) { //Quando uma tecla for pressionada
    var masks = ['000.000.000-000', '00.000.000/0000-01']; //Mascaras
    var mask = (cpf.length > 14) ? masks[1] : masks[0]; //Se for de tamanho 11, usa a 2 mascara
    $('#cpf').mask(mask, options); //Sobrescreve a mascara
}};

$('#cpf').mask('000.000.000-000', options); //Aplica a mascara
    
16.04.2018 / 02:06
0
You can use toggleClass and toggle mask

  

Following example code: |

$(document).ready(function() {



  $(".cpf_cnpj").mask("999.999.999-99").attr('placeholder', '000.000.000-00');
  
  $('.toggle').click(function() {
    $("#transaction_id").toggleClass('cpf_cnpj phone');
    $("#transaction_id").val('');
    $(".cpf_cnpj").mask("99.999.999/9999-99").attr('placeholder', '00.000.000/0000-00');
    $(".phone").mask("(999) 999-9999").attr('placeholder', '(999)999-9999');
  })



  $("#transaction_id").on("blur", function() {
    var last = $(this).val().substr($(this).val().indexOf("-") + 1);

    if (last.length == 3) {
      var move = $(this).val().substr($(this).val().indexOf("-") - 1, 1);
      var lastfour = move + last;

      var first = $(this).val().substr(0, 9);

      $(this).val(first + '-' + lastfour);
    }
  });
});
.toggle {
  display: inline-block;
  background: grey;
  border-radius: 5px;
  border: 1px solid #000;
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js"></script>
<div>
  <form role="search" class="navbar-form navbar-left" id="form2" name="form2">
    <div class="form-group">
      <label for="input">Clique para alternar</label>
      <div class="input-group">
        <span class="toggle">Alternar</span>
        
        <input type="text" name="transaction_id" id="transaction_id" class="form-control cpf_cnpj fone" placeholder="CPF, CNPJ ou Telefone" autofocus>
        

      </div>
    </div>
  </form>
</div>
    
16.04.2018 / 15:09