jquery – I can't change the validation mask when clicking 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 in the CPF or CNPJ through two RadioButtons, but the problem is that I can't change the field's mask when I switch between one option or another . I wanted that when the user clicked on CPf, the mask would assume the format of cpf and the same when clicking on cnpj. I'm making the page using ASP.net and also Jquery-Mask-Plugin. I don't know why, but the mask() function isn't working in my code, so I chose to use the data-mask attribute in the input itself. Here's 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>

Obs.: I've tried it in several ways, this code above is one of the times I implemented it.


Here is the jQuery script that you must implement to perform the mask change according to the option selected by the user, just adapt it to the ids of your inputs and the code in ASP.net that 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>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.0/jquery.mask.js"></script>

<input type="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">
Scroll to Top