jquery mascara formulario

Asked

Viewed 216 times

2

I am trying to validate the form field using jquery, if the size is larger than Cpf number it put 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");
    }

2 answers

2

If you want to get the value from inside the .cpfcnpj, you have to use .val(). By doing 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: http://jsfiddle.net/1tzhm01z/

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

  • yes but he does not apply the mask ...

  • which plugin you are using?

  • http://igorescobar.github.io/jQuery-Mask-Plugin/ this one

  • @Robertoaraujo on the link you submitted is there documented how you can do it. By entering this plugin link, navigate to the sections: On-the-fly Mask change and Mask as a Function in the code examples, there are two snippets of code exactly with that you want to do.

2


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

Here is the correct way to do this and also how it is 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);
  • I’m really going to study this function more but that’s what solved

Browser other questions tagged

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