Mask in dynamically generated fields

Asked

Viewed 546 times

-1

I need to add a mask with the jquery.Mask plugin in dynamically generated fields,

$(document).ready(function($){
    $('.mascara').mask('00000000');
});

for(var i = 0; i < data.d.length; i++)
{                               
   var linha = "<tr>";                          

   // Codigo Vestibular, Não retirar, está sendo usado no update de dados ao banco
   linha += "<td style='text-align:center'>"+data.d[i][0]+"</td>"; 
   // Descrição Vestibular
   linha += "<td class='mascara'>"+data.d[i][1]+"</td>"; 
   // dat1
   if (data.d[i][2] != "")linha += "<td contenteditable >"+data.d[i][2]+"</td>";
   else {linha += "<td contenteditable class='mascara'>Célula vazia</td>";}
   // dat2
   if (data.d[i][3] != "")linha += "<td contenteditable >"+data.d[i][3]+"</td>";
   else {linha += "<td contenteditable class='mascara'>Célula vazia</td>";}
   // dat3
   if (data.d[i][4] != "")linha += "<td contenteditable >"+data.d[i][4]+"</td>";
   else {linha += "<td contenteditable class='mascara'></td>";}
   // dat4
   if (data.d[i][5] != "" && data.d[i][5] != 0)linha += "<td contenteditable >"+data.d[i][5]+"</td>";
   else {linha += "<td contenteditable onkeyup='validaValor(this)'></td>";}                         

   linha += "</tr>";
   $('#corpotabela').append(linha);
   $('#combobox-vinculo'+i).val(data.d[i][2]);
}
  • What kind of mask do you want? CNPJ, CPF, CEP...

  • $('.mascara'). Mask('00000000');

  • These values are coming from Ajax?

  • Yes that’s right.

2 answers

1

Apply the mask after the dynamically generated fields. It is a possibility among others.

          $(document).ready(function(){
    
    
              var linha = '';
              for (var i = 0; i < 10; ++i) {
                  linha = $('<div>', {
                      class: 'a',
                      contenteditable: true,
                      style: 'border: 1px solid black'
                  });
                  $('#b').append(linha);
              }
              $('.a').mask('9999-9999');
          });
        
<!DOCTYPE html>
    <html>
      <head>
        <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js" ></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
    
    	</head>
      <body>
          <div id=b> </div>
      </body>
    </html>

  • One of the first things I tried, it doesn’t work

  • causes the following error: $(...). Mask is not a Function

0


How are you using contenteditable, can delegate the mask to dynamic elements when they receive focus using the syntax:

$(document).ready(function($){
   $(document).on("focus", ".mascara", function(){
      $(this).mask('00000000');
   });
});

Browser other questions tagged

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