I can not change the validation mask when I click on a RadioButton


I'm trying to make a mask for CPF and CNPJ within the same field, the user can choose whether to fill the CPF or CNPJ through two RadioButtons, but the problem is that I can not change the mask of the field when alternating between a option or another. I wanted that when the user clicked on CPf the mask assumed the format of cpf and the same when clicking on cnpj. I'm doing the page using ASP.net and also the Jquery-Mask-Plugin. I do not know why, but the mask () function is not working in my code, so I chose to use the data-mask attribute in the input itself. Here is my code:

$(document).ready(function () {

                 var $txtCpf = $("#<%=txtCPF.ClientID %>");
                 if ($("#<%=selectModeInsc.ClientID %> input").val() == "CPF"){
                    $txtCpf.attr("data-mask", "999.999.999-99");

                 $("#<%=selectModeInsc.ClientID %> input").click(function () {
                    if (valor == "CNPJ") {
                         $txtCpf.attr("data-mask", "99.999.999/0001-99");

<div class="col-lg-3">
                <div class="form-group">
                        ID="selectModeInsc" runat="server" RepeatDirection="Horizontal">
                        <asp:ListItem Text="CPF" Value="CPF" Selected="True"/>
                        <asp:ListItem Text="CNPJ" Value="CNPJ"/>
                    <asp:TextBox runat="server" ID="txtCPF" class="form-control" MaxLength="14" ></asp:TextBox>

Note: I have tried in several ways, this code above is one of the times I implemented.

asked by anonymous 05.07.2017 / 19:59

1 answer


Here is the jQuery script that you should implement to perform the mask change according to the option selected by the user, just fit it to the ids of your inputs and to the code in asp.net you have.

    var campo = $(this).val();
    if (campo == "cpf"){	
    else if (campo == "cnpj"){
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><scripttype="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.0/jquery.mask.js"></script><inputtype="radio" class="cpf-cnpj" id="cpf-cnpj" name="cpf/cnpj" value="cpf"> CPF<br>
<input type="radio" class="cpf-cnpj" id="cpf-cnpj" name="cpf/cnpj" value="cnpj"> CNPJ<br>
<label id="label-cpf-cnpj">CPF/CNPJ</label> <input type="text" id="InputCpf-cnpj" name="cpf/cnpj">
06.07.2017 / 12:51