jquery form mask

2

I'm trying to validate the form field using jquery, if the size is greater than the number of cpf it puts the cnpj mask in that same field

 var tamanho = $('.cpfcnpj').length;
    if (tamanho == 11){
        $(".cpfcnpj").mask('000.000.000-00',{reverse: true});
        alert("teste");
        }
    else if(tamanho > 12){
        $(".cpfcnpj").mask('00.000.000/0000-00',{reverse: true});
        alert("dois");
    }
    
asked by anonymous 19.11.2015 / 08:49

2 answers

2

When you do $('.cpfcnpj').val() , it brings the whole text completely, including the dots and dashes. That is, it will count the wrong size.

This is the correct way to do this and also as documented in the plugin itself: jQuery-Mask-Plugin

var SPMaskBehavior = function (val) {
  return val.replace(/\D/g, '').length < 12 ? '000.000.000-009' : '00.000.000/0000-00';
},
spOptions = {
  onKeyPress: function(val, e, field, options) {
      field.mask(SPMaskBehavior.apply({}, arguments), options);
    }
};

$('.akira').mask(SPMaskBehavior, spOptions);
    
19.11.2015 / 12:05
2

If you want to get the value from within .cpfcnpj , you have to use .val() . When you do this - $('.cpfcnpj').length; , it returns the number of elements with the class .cpfcnpj .

var tamanho = $('.cpfcnpj').val();
if (tamanho.length == 11) {
    $(".cpfcnpj").mask('000.000.000-00',{reverse: true});
    alert("teste");
}
else if (tamanho.length > 12) {
    $(".cpfcnpj").mask('00.000.000/0000-00',{reverse: true});
    alert("dois");
}

Example: link

  

You can read more about .val() here at this link: jQuery API Documentation .val ()

    
19.11.2015 / 09:31