Input Mask Razor

Asked

Viewed 1,235 times

0

I’m in need of help to include a CPF and CNPJ mask with Jquery or Js, so that it changes automatically after I click on a select, but I’m not able to include the mask inside the Razor I made.

@section scripts{
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/maskedinput")
<script>
    jQuery(function ($) {
        $("#xCpfCnpj").inputmask("99.999.999/9999-99");

    });
</script>
}
     <div>
            @Html.TextBoxFor(m => m.xCpfCnpj, new
       {
           htmlAttributes = new
           {
               @class = "form-control input",
               placeholder = "Cpf/Cnpj",
               type = "text",
               id = "xCpfCnpj"

           }
       })

        </div>

Here I tried 2 different ways to boot

  • Ah I understood sorry, I will already remove and post the code, thanks for warning

  • Are you validating in the model as well? The Jquery script block is at the top or end of the view?

  • At the end of the view and I’m validating on the model

  • [Required()] public string xCpfCnpj { get; set; }

1 answer

1

Use the .change of JQuery to make the mask change when switching options in the list.

$("#doc").mask("999.999.999-99");

$('#docType').change(function () {
    if ($('#docType option:selected').val() == 'CNPJ') {
       $("#doc").mask("99.999.999/9999-99");
    } else {
        $("#doc").mask("999.999.999-99");
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>

<select id="docType" name="doc">
<option value="CPF">CPF</option>
<option value="CNPJ">CNPJ</option>
</select>

<input id="doc" type="text" name="doc" />

Follow same example in jsfiddle: https://jsfiddle.net/Wurthmann/n1qsmbh0/1/

As for the problem of the mask not being applied is related to its JQuery. It may not be referenced or you may be rendering your script in the wrong place. But it’s hard to tell just from what you posted.

Check the browser console for an error. If no error has occurred check Source for pro calls JQuery are correct and if really rendered the stretch that should apply the mask.

Browser other questions tagged

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