Mask in dynamically generated fields

-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]);
}
    
asked by anonymous 15.03.2018 / 15:19

2 answers

0

Because you are using contenteditable , you 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');
   });
});
    
15.03.2018 / 16:20
1

Apply the mask after the dynamically generated fields. It is one 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><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
    
    	</head>
      <body>
          <div id=b> </div>
      </body>
    </html>
    
15.03.2018 / 15:47