How to Use Masks in Ajax

Asked

Viewed 464 times

0

I am developing an application and I am going through a difficulty when it comes to using Ajax, along with a plugin inputMask. I have some masks configured, but when it comes to using it in Ajax requests, they don’t work and I don’t know which direction to go.

Function of inputMask:

$('.input-cpf').inputmask({"mask": "999.999.999-99", "placeholder":"_"});

My input:

<input name="cpf" type="text" class="form-control input-cpf">

Could anyone help me? Which direction I need to take?

  • The CPF field is running without the mask during form submition with AJAX?

  • You can detail better what is not working?

  • First, is the input element already rendered in the DOM before you call inputMas? Another point this input is returning from AJAX as you may be loading inputMask into an element that is not yet in the DOM and when it is returned via AJAX the plugin function will not recognize the newly inserted element.

2 answers

0


I managed to solve. I put a click event inside the element, which called a function:

<input name="cpf" onclick="ajaxCPF()" type="text" class="form-control cpf-ajax">

And the function basically applied the mask, since as I said it was not loaded in the DOM

function ajaxCPF(){
    $('.cpf-ajax').inputmask({"mask": "999.999.999-99", "placeholder":"_"});
}

0

As we can see below, the mask is normally added to the input value.

$(function() {
  $('.input-cpf').inputmask({
    mask: "999.999.999-99"
  });

  $('.input-cpf').keypress(function() {
    console.log($(this).val());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://rawgit.com/RobinHerbots/Inputmask/3.x/dist/jquery.inputmask.bundle.js"></script>


<input name="cpf" type="text" class="form-control input-cpf" placeholder="CPF">

  • Marcus Italo, I believe that is the situation, I am very weak with javascript, even more Ajax. The mask works on other pages that have the refresh, but on this screen q ta via AJAX it n works, as if it had not been loaded.

Browser other questions tagged

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